use ternary operator to solve multiple conditions [closed] - ternary-operator

Can anyone please help me to solve this question. it doesn't work.

Take a look here:
class Question05
{
public static void main(String[] args)
{
double gpa = Double.parseDouble(args[0]);
String res = gpa >= 3.6?"First class Hons":(gpa<3.6 && gpa>=3.4?"Upper Second Class Hons": (gpa<3.4 && gpa>=3.0?"Lower Second Class Hons": (gpa<3.0 && gpa>=2.0?"Pass":"you have failed")));
System.out.println(res);
}
}
Edit: #veena, you were trying to assign a string to gpa, which was declared as a double!!!

I had this question before, and there are a few ways, depending on what you mean with the question...
As it does appear to be a class assignment, I will give my own examples rather than fix yours.
Scenario 1:
If you would like to have multiple passing conditions, consider the following...
Surround the conditions in parenthesis, just to be safe, and use logical separators.
eg:
(1==1 && 2==2)?"yay":"sadness"
https://jsfiddle.net/o4nu3ya5/
Scenario 2:
If you want to have conditions verified based on previous condintions verified, consider the following...
Just place a ternary within a ternary, possibly called a nested ternary??
eg:
1==1?2==2?"sweet":"almost":"not close"
https://jsfiddle.net/o4nu3ya5/1/
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator
Ternary are super fun. Get use to them, though understand, they will frustrate a lot of fellow developers as they are harder to read.

Related

Would you use the Action delegate to avoid duplication of code?

I just asked a question that helps about using generics (or polymorphism) to avoid duplication of code. I am really trying to follow the DRY principle.
So I just ran into the following code...
Sub OutputDataToExcel()
OutputLine("Output DataBlocks", 1)
OutputDataBlocks()
OutputLine("")
OutputLine("Output Numbered Inventory", 1)
OutputNumberedInventory()
OutputLine("")
OutputLine("Output Item Summaries", 1)
OutputItemSummaries()
OutputLine("")
End Sub
Should I rewrite this code to be as follows using the Action delegate...
Sub OutputDataToExcel()
OutputData("Output DataBlocks", New Action(AddressOf OutputDataBlocks))
OutputData("Output Numbered Inventory", New Action(AddressOf OutputNumberedInventory))
OutputData("Output Item Summaries", New Action(AddressOf OutputItemSummaries))
End Sub
Sub OutputData(ByVal outputDescription As String, ByVal outputType As Action)
OutputLine(outputDescription, 1)
outputType()
OutputLine("")
End Sub
I realize this question is subjective. I am just wondering about how religiously you follow DRY. Would you do this?
Seth
I've seen this called the "Hole in the middle" pattern. The "Real World Functional Programming" book mentions it. Here's a link.
http://enfranchisedmind.com/blog/posts/the-hole-in-the-middle-pattern/
See, there’s a pattern I’ve gotten
used to in Ocaml- and I’d even used it
in Perl, which I think of as the “hole
in the middle” pattern. The basic idea
is that you have two pieces of code
that are almost exactly identical,
except for that little middle part
there. The idea is that you factor out
the common code into a single
function, which takes a function
pointer as an argument. The middle
part in the shared code is replaced by
a call to the function pointer, and
the two places which are being
combined simply call the combined
function with a pointer to a function
that contains the unique part.
I wouldn't say I use it all the time, but I have used Action delegate to avoid code duplication. One scenario where I have used it is to wrap WCF calls (inside a client proxy) to avoid the same boiler plate code.
private void InvokeAndHandleFaults(
Action<Data, Context> wcfCall,
Data data,
Context context)
{
bool isSuccess = false;
try
{
wcfCall(data, context);
if (this.ChannelFactory.State != System.ServiceModel.CommunicationState.Faulted)
{
this.ChannelFactory.Close();
}
isSuccess = true;
}
catch (FaultException ex)
{
HandleFault(ex);
}
finally
{
if (!isSuccess)
{
this.ChannelFactory.Abort();
}
}
}
In terms of the example in the question, I would probably not use an Action. I would definitely not refactor to use an Action. Mainly because the actual logic is quite simple so I don't see much benefit. As the "complexity"/size of the repeated code increased I would be more likely to use a delegate.

Haxe: “Int cannot be called”

This one really got me for a while.
Problem
If you're reading this question, perhaps you're getting a mysterious "Int cannot be called" message
103: characters 22-29 : Int cannot be called
when you try to compile your Haxe application.
Solution
Consider that you may be adding parentheses where they don't belong. For example, I have a class with public variable level
public var level(getLevel, setLevel):Int;
but was mistakenly referencing it, elsewhere, using parentheses
var charLevel:Int = c.level();
when I should have omitted the parentheses
var charLevel:Int = c.level;
Don't know why I did this, but I hope the information helps.

Single return point or multiple inline returns?

I often see a piece of code similar to the following (language doesn't matter):
private Result method() {
var result = initialValue;
if (condition) {
result = otherResult;
}
return result;
}
And here is a little bit refactored version:
private Result method() {
if (condition) {
return otherResult;
}
return initialValue;
}
Pros of the first solution as authors say is the single return point in the method. From my point of view the second variant is much better without additional variable despite the two return points. Also in case condition is true the value of result becomes to be set twice.
Do any additional pros and cons exist here? What case is better nevertheless?
Whatever way you write your code, compiler tries to generate the best possible/optimized code. You can try to see the generated assembly code for both and see whether it really makes difference or not. But from code simplicity point of view, first one looks better.
It depends what you're doing really.. In this simplified example it may not be apparent, but the first way is better if you need to do something after checking the condition regardless of what the result is.
This is not possible in the second version since the function instantly returns. Any code written after the if block will not be executed if the condition passes.

How do I name the function which only does something if condition is true

According to clean code laws, we want to have functions which do only one thing and are on the same "level of abstraction". But how to name function, whose work is just to check some condition and do the work if condition is true. For example, how could this function be named?
public void HowToNameThis(){
if(!ComponentIsInstalled()){
DisableCheckbox();
}
}
I thought about naming it like DisableCheckboxIfComponentIsNotInstalled, but then the name just repeats the code, which effectively means I have created a function but did not create any abstraction.
CleanCode also suggest that you stay as positive as you can in your code. If you reverse the logic within your method, then, naming becomes easier.
public void TryEnableComponent() {
if(ComponentIsInstalled()) {
EnableCheckbox();
}
}
I generally think really hard about if the IF is really deserving it's own function.
And then often end up inlining it:
Like this (pseudo):
void SetupInstallerWindow()
{
LoadLicenseAgreement();
if(!ComponentIsInstalled()){
DisableCheckbox();
}
BringWindowTop();
}
If that really gets to messy, here's an idea for a name might provide more context for the reader:
AllowReinstallationOfComponent()

Style of if: to nest or not to nest

A colleague of mine and me had a discussion about the following best-practice issue.
Most functions/methods start with some parameter checking.
I advocate the following style, which avoids nesting.
if (parameter one is ugly) return ERROR;
if (parameter two is nonsense || it is raining) return ERROR;
// do the useful stuff
return result;
He, who comes from a more functional/logic programming background, prefers the following, because it reduces the number of exit points from the function.
if (parameter one is ok) {
if (parameter two is ok && the sun is shining) {
// do the useful stuff
return result
}
}
return ERROR;
Which one would you prefer and why?
I personally prefer the first style, since I feel that it provides some logical separation between what we can call "error cases" and "method logic". There is a well defined block in the beginning of the method that evaluates and acts on any errors in the input, and then the rest of the method is all about what the method should actually do.
It's some sort of separation of concerns on the micro level, I guess.
As long as the style is consistent across the codebase, any of these two styles would be ok with me.
In the case of two checks then either is ok really, once you add more, option 1 quickly becomes more and more desirable!
I prefer to do all my input parameter validation at the beginning of the function and do a return there only. Hence I prefer the first approach most of the times. If there is only one level of nesting then I might go for the second option.
The second one I'd prefer usually, unless the whole function body will be wrapped in the X number of if statements. If so, I'd choose the first option.
I prefer the first. 5298529357 levels of indents just grates on my nerves.
Add to that the fact that when you return right away, it's obvious that (parameter one is ugly) is an error.
The most readable style is:
if (parameter one is ok)
{
if (parameter two is ok && the sun is shining)
{
// do the useful stuff
return result
}
else
{
// do other things
}
}
return ERROR;
At least for me :)
EDIT: Sorry, misunderstood the question. I vote for the first, don't like deep nesting.
In my opinion it only depends on the type of error checking you need.
If for example parameter one is ugly but in the following code you can manage to change it's state to pretty the second method is preferable.
However if the error is fatal and cannot be handled you should return immediately.
There is a third option here where the second style fits the most and it is when you want to gather all of the errors into one coherent error message.
The second style shouldn't check for validness but for non-validness first.
As for personal preference I'd be much happier with the first style.
Our in-house style is to avoid multiple return points and also to limit the amount of nesting, so I'd probably combine your pre-condition sanity checks together and do something like:
result_t result = OKAY;
// Sanity checks
if ((parameter_one == ugly) || (parameter_two == nonsense) || (weather == raining))
{
result = ERROR;
}
else
{
// do the useful stuff
}
return result;

Resources