Can anyone help me to understand this line? I tried to transform it with "if .. else" but it didn't work. Thanks in advance.
return (patient1.isEmergencyCase() == patient2.isEmergencyCase()) ? (Integer.valueOf(patient1.getId()).compareTo(patient2.getId())) : (patient1.isEmergencyCase() ? -1 : 1);
if (patient1.isEmergencyCase() == patient2.isEmergencyCase()) {
return Integer.valueOf(patient1.getId()).compareTo(patient2.getId());
} else if (patient1.isEmergencyCase() ) {
return -1;
} else {
return 1;
}
In other words, it's a sorting, probably to decide which patient comes first. You would typically find such a code in a compareTo method, which is typically used to sort lists, in this case to define who gets "served" in which order.
It returns -1 if partient1 is "lesser/earlier/etc", which happens if both of them are emergency cases and patient1's id is lower OR if only patient1 is an emergency case, otherwise it returns 1 (or 0, is both are emergency cases and their ids are equals).
You can have a look if the concept isn't yet clear: Comparable.
if (patient1.isEmergencyCase() == patient2.isEmergencyCase()) {
return Integer.valueOf(patient1.getId()).compareTo(patient2.getId());
} else {
if (patient1.isEmergencyCase())
return -1;
else
return 1;
}
This is what has been condensed into the nested ternary expression.
The first step in understanding is to convert the expression inside the else into a ternary, and then work your way outwards.
That is,
if (patient1.isEmergencyCase())
return -1;
else
return 1;
is equivalent to return patient1.isEmergencyCase() ? -1 : 1.
But this expression itself is under the else condition.
What the code is doing is that if both patients are emergency cases, or both are non-emergency cases, then prioritize the one whose id comes first (according to the compareTo method). If, however, one patient is an emergency case while the other is not, then prioritize the emergency patient ... quite a realistic situation.
It's just like this:
if(patient1.isEmergencyCase() == patient2.isEmergencyCase()){
return Integer.valueOf(patient1.getId()).compareTo(patient2.getId());
} else {
if(patient1.isEmergencyCase()){
return -1;
} else
return 1;
}
It's a short way to write the same thing. Put the condition to evaluate before the '?' character, the put the two condition true : false.
Simple!
You should use nested if-else for producing output from this line....here multiple ternary operators are used ...
ternary operator---- condition?true statement :false statement;
Related
I am using BlueJ IDE to write java programs.
I have a method with String return type. I have put the return statements within if-else, such that if the boolean variable "flag" has true value, then one value is returned, while if the value is false, another value is returned.
Now, the problem is that BlueJ asks for another return statement even after this, as shown below.
If I give another return after if-else, it works.
Why is this happening? I had learnt that there can be no statements after the return statement. So, why is the compiler asking for another return statement?
If someone wants the code for cut-paste purposes, here it is. This code is meant to convert binary numbers to their decimal equivalents, including fractions, but no negative numbers.
public class Conversions{
protected String Binary_Decimal(String str){
int a = str.indexOf('.');
boolean flag = false;
if (a == -1){
str += ".0";
a = str.indexOf('.');
flag = true;
}
String bd = str.substring(0, a);
String ad = str.substring(a + 1);
a = 0;
double num = 0;
for (int i = bd.length() - 1; i >= 0; i--){
num += Math.pow(2, a) * Integer.parseInt(Character.toString(str.charAt(i)));
a++;
}
if (flag == true){
return Integer.toString((int) num);
}
else if (flag == true) {
a = -1;
for (int i = 0; i < ad.length(); i++){
num += Math.pow(2, a) * Integer.parseInt(Character.toString(str.charAt(i)));
a--;
}
return String.valueOf(num);
}
return String.valueOf(num); //<-- WHY DOESN'T IT RUN WITHOUT THIS EXTRA return?
}
}
Here, str is the string that is input by the user using a different method Input().
The issue is that you wrote an if - else as an if - else if. The compiler does not understand or care that the two conditions you have are mutually exclusive and therefore cover all cases. Given how you wrote the branches, you need an explicit else or a catchall return for the compiler to be assured that the function always returns a String.
This is one example of why it is a bad idea to explicitly spell out the else when you have a set of conditions. The more important reason being that your if will often contain something much more complex and you might not negate it properly.
Delete the second ELSE IF clause and put the block directly after the first return statement, and consider that flag is a boolean. As follows:
if (flag) return Integer.toString((int) num);
a=-1;
for(....){
....
}
return String.valueOf(num);
In this way, the compiler should not notify you that error.
So, why is the compiler asking for another return statement?
Because you are missing a default return statement.
What if none of the conditions you have satisfied ? There must be something return default right ? That is what the issue is. That is why it is getting compiled when you uncomment that line.
Or even , you have an else statement, your program will have at least one satisfied return and it gets compiled too. Try it.
I had learnt that there can be no statements after the return statement.
This statement comes with some conditions. You have the return statement inside the if condition. So if your expression is not true, there is no way that the return gets execute.
So I'm defining a recursive function that takes as an argument a value for x (like the arithmetic variable x, i.e. "x + 3 = 5") and returns the result of the arithmetic expression. The expression is taken from a Binary expression tree that looks like this:
You start at the root and keep working your way down till you hit the leaves, and once you do you come back up. The expression on the tree is then:
x * ( (x + 2) + cos(x-4) ).
My code for this function is as follows:
// Returns the value of the expression rooted at a given node
// when x has a certain value
double evaluate(double x) {
if (this.isLeaf()) {
//convert every instance of 'x' to the specified value
if (this.value.equals("x")) {
this.value = Double.toString(x);
}
//return the string-converted-to-double
return Double.parseDouble(this.value);
}
//if-else statements to work as the arithmetic operations from the tree. Checks the given node and performs the required operation
else {
if(this.value.equals("sin")) { return Math.sin(evaluate(Double.parseDouble(this.leftChild.value))); }
if(this.value.equals("cos")) { return Math.cos(evaluate(Double.parseDouble(this.leftChild.value))); }
if(this.value.equals("exp")) { return Math.pow(evaluate(Double.parseDouble(this.leftChild.value)), evaluate(Double.parseDouble(this.rightChild.value))); }
if(this.value.equals("*")) { return evaluate(Double.parseDouble(this.leftChild.value)) * evaluate(Double.parseDouble(this.rightChild.value)); }
if(this.value.equals("/")) { return evaluate(Double.parseDouble(this.leftChild.value)) / evaluate(Double.parseDouble(this.rightChild.value)); }
if(this.value.equals("+")) { return evaluate(Double.parseDouble(this.leftChild.value)) + evaluate(Double.parseDouble(this.rightChild.value)); }
if(this.value.equals("-")) { return evaluate(Double.parseDouble(this.leftChild.value)) - evaluate(Double.parseDouble(this.rightChild.value)); }
}
}
However the compiler is tossing an error telling me that my function must return a type double. Both the if and the else statements return a double- the if statement directly and the else statement through the sum of 2 doubles returned by the same function. What is the deal here? If I place a return statement outside of the if-else then the error resolves itself but to work with that would require me to keep a static or a global variable consistent through each recursion. I'd like to know what is wrong with my function as is, because it feels much more intuitive than a global variable and I think I'm missing a key concept about recursion here. Any help is appreciated- thank you!
Both the if and the else statements return a double
They actually don't. The if branch always does, but the else branch doesn't. What happens if this.value equals "Invalid", or something else which isn't in your list? Then it won't ever hit a return statement. Since it's required to always return, or throw an exception, this isn't allowed.
Even if you have your program structured in such a way that it logically always has to return a value, the compiler isn't going to be doing complex analysis on all the branches of your program to ensure that it always returns something. It just checks that each branch has a valid return.
So, for example, something like is invalid
if(x < 0) return -1;
if(x >= 0) return 1;
Because the compiler doesn't know that it always has to hit one of those two conditions (an issue which is further complicated by the fact that, depending on what x is, it might not always have to go down one of those branches).
Instead, your code should be structured like this:
if(x < 0) return -1;
else return 1;
So that every branch has a valid exit condition.
I want to know whether there is a performance difference in following two code blocks
1>
if(name == null) {
//something
}
if(name != null) {
//something
}
and
2>
if(name == null) {
//something
}
else {
//something
}
The first compares twice, the second compares once. The difference will not be noticeable, but it's there.
after benchmarkint it on 100.000.000 iterations, the first execution costs 719ms and the second 703ms.
I used a modulo so the conditions has to change every turn and avoid precompiled result. Please find the code below. I have noticed that this gap reduces when number of iterations increases.
public static void main(String[] args) {
Date start1 = new Date();
for(int i=0; i<100000000; i++) {
int it = i%2;
if(it == 0) {
double j = Math.random();
j++;
}
if(it != 0) {
double j = Math.random();
j++;
}
}
Date end1 = new Date();
Date start2 = new Date();
for(int i=0; i<10000000; i++) {
int it = i%2;
if(it == 0) {
double j = Math.random();
j++;
} else {
double j = Math.random();
j++;
}
}
Date end2 = new Date();
System.out.println((end1.getTime()-start1.getTime())+" / "+(end2.getTime()-start2.getTime()));
}
Just a brief comment to say that the compiler cannot optimize it in all cases, because name is visible within the first if block therefore it could have been modified in it, so it has to be checked again in the second if condition. Imagine this case:
if (name == null) {
// Does something
name = "Did it.";
}
if (name != null) {
// Does something else
}
It's clearly not equivalent to
if (name == null) {
// Does something
name = "Did it.";
} else {
// Does something else
}
If what you actually mean is that you should do something in one case and something else otherwise, please use if { ... } else { ... } - not just for (minimal) performance improvement, but also because your code should reflect what you actually mean.
Note that the two fragments are not necessarily equivalent, because the first block could re-assign name so that the second condition will also be true.
This can introduce hard to spot bugs, so I suggest that (before thinking about performance), you think about making the variable final if possible and use if/else when it makes sense (i.e. it should enter only one of the two branches) and chained if's when that makes sense (for example when the first if can establish a default value for the next one to use).
Yes there will, on the second one only one condition will be checked and on the first one two conditions would have to be checked.
An if clause that fails its evaluation has to make an "instruction jump" even if there is no else statement follwing it.
Assuming the first if is false, you'd be comparing these 2 execution scenarios:
1>
Check 1st condition
Skip to check 2nd condition
Do "something" inside the 2nd condition
2>
Check condition
Skip to "something" inside the else
Yes becuase both if cases will be evaluated in the first whereas only one if will be evaluated in the second.
yes, there will be a difference: in the second example, tehre's only 1 statement to be proofed, in the first one there are two.
but: the difference in performance will be absolutely minimal, in 99% of the cases you won't even notive any difference - make sure your code is as readable as it can be, thats much more important ;)
yes obviously the second code will perform inconsiderably better, because there is only one condition to check
I believe the compiler is smart enough to notice that the second if in the first example is redundant, so there won't be any performance change
I've seen this before in code, but forgotten it. Basically it toggles a boolean variable. If it's true, it'll set to false and vice-versa. But unfortunately forgot the syntax.
It's basically a one liner for this:
if (myVar) {
myVar = false;
} else {
myVar = true;
}
It's something like this, but don't know what it's called or the correct syntax of it:
myVar = myVar : false ? true;
How about
myVar = !myVar
?
myVar = myVar ? false : true; is using the conditional operator.
You can just do this though
myVar = !myVar;
Another option is XOR:
myVar ^= true;
It's notable in that only the LHS of the assignment ever changes; the right side is constant and will toggle any boolean variable. Negation's more self-documenting IMO, though.
What you are thinking of is the conditional operator:
myVar = myVvar ? false : true;
(As you see, a lot of people call this "the ternary operator", but that only means that it is an operator with three operands. As it happens, there is only one operator with three operands in this language, but it still says nothing about what the operator does.)
It's of course easier to use the negation operator:
myVar = !myVar;
The smallest code I can think of at the moment. I don't know what its called (if it has a name, as you seem to suggest)
myVar = !myVar
What you're talking about is the "ternary" or "conditional" operator, which does an inline substitution as per a condition.
The syntax is:
condition ? trueValue : falseValue
I usually throw parentheses around my condition, sometimes around the whole conditional operator. Depends on how much I'm trying to delineate it from everything else.
So for example, suppose you want to return the larger of two numbers:
public int max(int a, int b)
{
return (a > b) ? a : b;
}
Notice that it can be substituted into the middle of something else.
Okay, now let's tackle your actual question about toggling a boolean type.
myVar = (myVar) ? false : true;
is how you would do it with the conditional operator. (Again, parentheses aren't required, I just favor them.)
But there's a simpler way to toggle the boolean... using the logical NOT ("!") operator:
myVar = !myVar;
Keep it simple. :-)
if(myVar == true)
{
myVar = false;
}
else if (myVar == false)
{
myVar = true;
}
else
{
myVar = FILE_NOT_FOUND
}
This also works :P
v=v?!v:!v;
There is a ternary operator (wikipedia). Which allows you to write a condensed if-else statement like in the second example.
In java:
myVar = (myVar) ? true : false;
There is also the NOT operator, which toggles a boolean variable. In java that is !. I believe that is what you want.
myVar = !myVar;
public boolean toggle(boolean bool)
{
return !bool;
}
I recently (on my own) found a similar answer to one already stated here. However, the simplest and shortest (non-repeating variable name with least code) answer is:
formControl.disabled ^= 1;
This works best in JavaScript when wanting to toggle boolean, DOM-based attributes (for example, a form control/input's disabled property -- going from a non-editable to edit state). After much searching (with no result that I liked) and some trial and error, I found my solution to be the simplest (however, true instead of a 1 would be clearer -- as was previously posted).
Since this syntax isn't very clear, immediately, I would not advise using it very often (I believe it is appropriate when the variable or property makes the context obvious). I have posted this response (instead of making it a comment) because the context in which the XOR bitwise self-assignment should be used is very important. This "trick" should mostly be avoided when considering best practices.
As others have noted, there are two ways to negate something: "lvalue = !lvalue;" and "lvalue ^= 1;". It's important to recognize the differences.
Saying "lvalue = !lvalue" will cause lvalue to be set to 1 if it was zero, and 0 if it was set to anything else. The lvalue will be evaluated twice; this is not a factor for simple variables, but saying "someArray[index1][index2][index3][index4] = !someArray[index1][index2][index3][index4]" could slow things down.
Saying "lvalue ^= 1;" will cause lvalue to be set to 1 if it was 0, 0 if it was 1, and something else if it was neither zero nor 1. The lvalue need only be specified or evaluated once, and if the value is known to be either zero or 1, this form is likely to be faster.
Too bad there's no auto-negate operator; there are times such a thing would be handy.
You can also use the binary form of negation as shown here.
if ((v == true) && !(v = false)) {
v != true; /* negate with true if true. */
} else {
v =! false; /* negate with false if false. */
}
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
The code:
public String getTemperatureMessage(double temp)
{
if(temp < 32)
return "Freezing";
else if(temp < 60)
return "Brr";
else if(temp < 80)
return "Comfortable";
else
return "Too hot";
}
Regarding the code snippet above, the else ifs are technically superfluous and don't change the behavior at all. However, I tend to like to put them in there to emphasize that the conditions are exclusive. What are your thoughts? Unnecessary or more clear?
The only feasible alternative in this particular case is to grab the conditional operator ?:.
public String getTemperatureMessage(double temp) {
return temp < 32 ? "Freezing"
: temp < 60 ? "Brr"
: temp < 80 ? "Comfortable"
: "Too hot";
}
Left behind the question how that's readable to starters.
References
JLS 15.25 Conditional Operator ?:
The operator is right-associative, thus such nesting of the operator will work "as expected"
Related questions
To ternary or not to ternary?
It depends on a lot of things like how complex your code is. With a simple example like this, I'd put the returns on the same line as the ifs, and not use elses. The structure and behaviour is clear:
public String getTemperatureMessage(double temp)
{
if(temp < 32) return "Freezing";
if(temp < 60) return "Brr";
if(temp < 80) return "Comfortable";
return "Too hot";
}
When I have more complex code I find it useful to not break out from the nesting with returns or continue/break, but to assign to state or result variables. I will then also include {} even if the block is a single statement, mostly to keep the consistency in how the structure is represented in code, but also to slightly reduce the risk that later edits will forget to change a statement to a block.
If this example was more complex, I'd probably code it like this:
public String getTemperatureMessage(double temp) {
String result;
if(temp < 32) {
result = "Freezing";
} else {
if(temp < 60) {
result = "Brr";
} else {
if(temp < 80) {
result = "Comfortable";
} else {
result = "Too hot";
}
}
}
return result;
}
If a function has multiple "successful" return values, I'll use if/else to select among them. If a function has a normal return value, but one or more ways that may abnormally exit early, I generally won't use an "else" for the normal path. For example, I think it's far more "natural" to say:
int do_something(int arg1)
{
if (arg1 > MAX_ARG1_VALUE)
return ARG1_ERROR;
... main guts of code here
return 0;
}
than to say:
int do_something(int arg1)
{
if (arg1 > MAX_ARG1_VALUE)
return ARG1_ERROR;
else
{
... main guts of code here
return 0;
}
}
or
int do_something(int arg1)
{
if (arg1 <= MAX_ARG1_VALUE)
{
... main guts of code here
return 0;
}
else
return ARG1_ERROR;
This distinction becomes especially significant if there are multiple things that can "go wrong", e.g.
int do_something(int arg1)
{
if (arg1 > MAX_ARG1_VALUE)
return ARG1_ERROR;
... some code goes here
if (something_went_wrong1)
return SOMETHING1_ERROR;
... more code goes here
if (something_went_wrong2)
return SOMETHING2_ERROR;
... more code goes here
if (something_went_wrong3)
return SOMETHING3_ERROR;
return 0;
}
Nested 'if/else' statements in such cases can get ugly. The most important caveat with this approach is that any cleanup code for early exits must be given explicitly, or else a wrapper function must be used to ensure cleanup.
Some would say that multiples return would be the problem here. But it's not really my point.
For my point of view, the if/else if is really important, because even if in your case you return some value, removing the elses would mean that you wouldn't put them anyway, and that would mean a totally different thing if the returns were not here.
Plus, imagine someday someone want to edit your code, and clean it up for a single return, this person could misunderstand your code and do a grave mistake like this :
public String getTemperatureMessage(double temp){
String message;
if(temp < 32)
message = "Freezing";
if(temp < 60)
message = "Brr";
if(temp < 80)
message = "Comfortable";
else
message = "Too hot";
return message;
}
To clarify my point of view, keep the elses, it keep your code clear.
For simple 1-liners I tend to leave out the else but if there's more complex if blocks I tend to prefer the else to make it clear that the conditions are mutually exclusive.
public String getTemperatureMessage(double temp)
{
String retval = null;
if(temp < 32)
retval = "Freezing";
else if(temp < 60)
retval = "Brr";
else if(temp < 80)
retval = "Comfortable";
else
retval = "Too hot";
return retval;
}
For a simple if statement without too many lines of code having multiple returns is no problem. However, nothing infuriates me quite so much as:
function doTemperatureCalculations(double temperature) {
if (temperature < 20) {
/*
Gazillion lines of code here .....
*/
return "Very cold!";
} else if (temperature < 40) {
/*
Another gazillion loc .....
*/
return "Summer in the North Pole.";
} else {
/*
Multiple returns embedded throughout ....
*/
}
}
In this case it is more clear. In the general case you may want to leave the elses off as they can contribute to more nesting and code complexity. For example:
if (error condition) {
do some stuff;
return;
} else {
do stuff;
if (other error condition) {
do some stuff1;
return;
} else {
do some other stuff;
return
}
}
The code below keeps the level of nesting down which reduces code complexity:
if (error condition) {
do some stuff;
return;
}
do stuff;
if (other error condition) {
do some stuff1;
return;
}
do some other stuff;
return;
In your example it is easy either way. But in many cases you would be better off using a lookup table for this sort of thing and reading the values from a file/database. For efficiency in C often this would be coded as an array of structs.
The else does add some clarity in that it makes it clear that the cases are mutually exclusive. However the idiom of returning like you do is obvious to many programmers, so either way the majority will know what you meant.
I can think of an advantage of the elses. If you want to add a new last case, without the elses you might forget to add an if to the currently "Too Hot Condition" if say you wanted to add "Dying" at 120 or something. while with the elses you know that you need the final else to be in front of "Dying" so you will be more likely to think about putting the else if in front of "Too Hot". Also if you just put an else on "Dying" you will get a compile error which forces you to think.
Personally, I think the elses are unnecessary. Since this question is tagged as [language-agnostic], I'm going to provide a couple of examples of how I would write it:
def temperature_message(temp)
return 'Freezing' if temp < 32
return 'Brr' if temp < 60
return 'Comfortable' if temp < 80
'Too hot'
end
This is typical guard clause style, which both I personally and the Ruby community in general use quite often.
def temperature_message(temp)
case
when temp < 32
'Freezing'
when temp < 60
'Brr'
when temp < 80
'Comfortable'
else
'Too hot'
end
end
This is a typical switch as you would find it in some less powerful languages. This is probably one that I would not use, I would refactor it like this:
def temperature_message(temp)
case temp
when (-1.0/0.0)...32
'Freezing'
when 32...60
'Brr'
when 60...80
'Comfortable'
else
'Too hot'
end
end
Although I must admit I still find the first one easiest to read.
Since this is basically a mapping table, I would try to format it as such, so that everybody who reads the code, immediately sees the "table-ness":
def temperature_message(temp)
case temp
when (-1.0/0.0)...32 then 'Freezing'
when 32...60 then 'Brr'
when 60...80 then 'Comfortable'
else 'Too hot'
end
end
This also applies to your original Java implementation:
public String getTemperatureMessage(double temp) {
if(temp < 32) return "Freezing";
if(temp < 60) return "Brr";
if(temp < 80) return "Comfortable";
else return "Too hot";
}
Of course, since it is basically a mapping table, you might just as well implement it as a map:
def temperature_message(temp)
{
(-1.0/0.0)...32 => 'Freezing',
32...60 => 'Brr',
60...80 => 'Comfortable',
80..(1.0/0.0) => 'Too hot'
}.detect {|range, _| range.include?(temp) }.last
end
The redundant elses make me cringe. The extra syntax and indentation makes it harder for me to read. I just got through removing a bunch of these from some code I inherited.
Most cases of redundant code are mistakes, so by implication a redundant 'else' looks like a mistake to me even if you put it there on purpose. The impression I get is of code that was originally written without embedded returns, then someone rewrote it to have the embedded returns, but they were too lazy to remove the elses.
A single if/return is easy to understand; so are 4 in a row. It's "that case is done; let's move on". A long chain of if/elses can be a pain to read; you need to read all the way to the bottom before you find out what happens. The saving grace is it allows a single return to be used -- a feature that is overrated IMO but I'll admit it does provide some value. However a long chain of if/elses combined with returns mixed in amongst the elses is the worst of both worlds -- all the disadvantages of multiple returns, and made to look like one large construct you have to get in your head all at once. Ugh.
From a theoretical perspective consider this: The zone between the return and the else is essentially unreachable code. Sure, it only contains whitespace, but the zone shouldn't even be there at all.
Finally, an example of if/return/else taken to its redundant conclusion. I've seen a few of these lately. Why in the world is there an else block? The code in the else block executes under the same conditions as the code directly after it:
...
if (temp < 35)
{
foo.status = TOO_COLD;
return;
}
else
{
foo.status = TEMP_OKAY;
}
launch_the_rocket(now);
return;
I agree that the elses makes it more clear. The final else especially helps to make a visual distinction between the case where every branch has a return, and the cases where only some branches have a return (which could be a smell).
There's no point. You're adding needless semantic and other overheads for absolutely zero benefit. When you return, you return and control is over. Pretending anything else is superfluous and just makes you look like you don't know what the return statement does.
Who uses IF/ELSE IF... when you can use a SWITCH statement?
My preference is for the single RETURN statement - multiple return statements can make debugging a pain...
I don't think I'd write in this way in the first place, but going along with the premise, I'm guessing that any compiler would crank out the same code whichever method you chose to write, so there is no technical reason that I can think would favour one over the other.
The argument is therefore Single or Compound statement.
I think the rule of "least surprise" should be used, which in this case would call FOR the superfluous else statements to be included.
PS. I would always send a temperature in degrees centigrade, oops, just broke your function!
it's good. without "else", this line
if(temp < 80)
return "Comfortable";
would be unconvincing. with "else", it's clear that there are other preconditions.
I prefer case statements myself but that would make this a language specific topic and not language-agnostic topic.
Dim Temp As Integer
Dim Message As String
Select Case Temp
Case Is < 32
Message = "Freezing"
Case Is < 60
Message = "Just Right"
Case Is < 80
Message = "Too Hot"
Case Else
Message = "What was I doing?"
End Select
I find these alot easier to read then if..else statements.