Resharper is telling me that the 'else' in this code is redundant:
if(a)
{
//Do Something
}
else if(b)
{
//Do Something
}
The else does not seem redundant because the else keeps b from being evaluated if a is true. The extra overhead is small if b is a variable, but b could also be an expression.
Is this correct?
It's redundant if you have a some sort of break, continue, return, or throw statement (or even a goto) inside the first if-block that always causes execution to branch outside the current block:
if(a)
{
return 0;
}
else if(b)
{
return 1;
}
In this case, if the code enters the first block, there's no way it will enter the second block, so it's equivalent to:
if(a)
{
return 0;
}
if(b)
{
return 1;
}
You are right in this case, but this is the reason I think they had it to begin with:
Certain if-else conditions can have their else clause removed. Consider the following method:
public int Sign(double d)
{
if (d > 0.0)
return 1;
else
return -1;
}
In the above, the else statement can be safely removed because its if clause returns from the method. Thus, even without the else, there’s no way you’ll be able to proceed past the if clause body.
It doesn't appear redundant to me. Removing the else would result in different program flow if both a and b are true.
Related
I have a method that checks multiple conditions to execute further, only to proceed to next if the current condition evaluates to false, otherwise the method will exit without evaluating further conditions. And the number of conditions vary in different implementations (subclasses).
I'm limited by my creativity to make it look any better than using the dreaded goto statement. Is there any better way to do the following:
public bool DoSomething()
{
bool result = true;
if (exclusion1)
{
result = false; goto Exit_Now;
}
if (exclusion2)
{
result = false; goto Exit_Now;
}
if (exclusion3)
{
result = false; goto Exit_Now;
}
if (exclusion4)
{
result = false; goto Exit_Now;
}
if (exclusion5)
{
result = false; goto Exit_Now;
}
if (result)
{
//do something
}
Exit_Now:
return result;
}
EDIT: In response to the answers, I understand using "else if" and conditional OR '||' operator are the obvious choices:
Subquery: which is more performant? I ask because this happens inside a loop and each evaluation takes about 30-40 ms. What is supposed to be finished in under a minute is taking up to two minutes without the goto statements in the code given above. Hence, the query. Thanks for all the help.
If you can fit your exclusion tests into the if statement, just use else if statements;
if (exclusion1)
{
result = false;
}
else if (exclusion2)
// etc ...
else if (result)
{
//do something
}
But I find it's much simpler, and easier to read, to just return early;
if (exclusion1)
return false;
One way to simplify this is to treat the exclusions as a guard clause:
public bool DoSomething()
{
if (exclusion1 ||
exclusion2 ||
exclusion3 ||
exclusion4 ||
exclusion5)
{
return false;
}
//do something
return true;
}
This also has the benefit of removing the nesting of the //do something towards the end.
you can always do this:
result = !(exclusion || exclustion2 ...|| exclusionN);
I have a couple IF statements and am trying to figure out how to have the first If statement execute something and not the second but if the first is not true then execute the second one.
if (condition)
{
do_something;
}
if(condition_2)
{
do_something_also;
}
I want the first if statement to happen but after it executes I want it to skip the second if statement.
If the first do_something happens I want to skip the second if statement completely.
How do I go about doing this?
Use else if:
if (condition)
{
do_something;
}
else if(condition_2)
{
do_something_also;
}
Just use if - else if...
if(condition){
do_something();
} else if (condition2){
do_something_also();
}
I am currently studying the conditional constructions. Correct me if I am wrong but else if and else(if(){}) is the same thing... Example:
a=5;
if(a==6)
{
Console.WriteLine("Variable 'a' is 6");
}
else if(a==5)
{
Console.WriteLine("Variable 'a' is 5");
}
And
a=5;
if(a==6)
{
Console.WriteLine("Variable 'a' is 6");
}
else
{
if(a==5)
{
Console.WriteLine("Variable 'a' is 5");
}
}
Are these things the same? And if yes why does else if exist if I can write it the "second way"(the second example that I wrote)?
Yes, these are effectively identical.
The reason the "else if" statement exists is to make cleaner code when there are many conditions to test for. For example:
if (a==b) {
//blah
} else if (a==c) {
//blah
} else if (a==d) {
//blah
} else if (a==e) {
//blah
}
is much cleaner than the nested approach
if (a==b) {
//blah
} else {
if (a==c) {
//blah
} else {
if (a==d) {
//blah
} else {
if (a==e) {
//blah
}
}
}
}
why does else if exist
It doesn't. It's not a keyword or construct on its own. Your two examples are identical except that in the second case you've added some superfluous braces and whitespace into the code.
if and else are both simply followed by a single statement. In your first example the statement following the else is:
if(a==5)
{
Console.WriteLine("Variable 'a' is 5");
}
The second example just wraps that same statement in braces, and adds a new line at the start. The new line is ignored, so it doesn't change the semantics, and as the code is already a single statement, wrapping it in braces doesn't change it in any way.
Strictly speaking, there is no such thing as an else if statement. An "else if" is actually just in essence an else with a single line body that happens to be the start of an entirely separate if statement. You can visualize it like this:
var a = 5;
// This if uses a single line
if (a == 6) DoSomething();
// This else is a single line that is also a single-line if
else if (a == 4) DoAnotherThing();
// This else uses a single line as well, but is referring instead to the second if
else DoSomethingElse();
The above script is identical to the following:
if (a == 6)
{
DoSomething();
}
else
{
if (a == 4)
{
DoAnotherThing();
}
else
{
DoSomethingElse();
}
}
Or even this:
if (a == 6)
DoSomething();
else
if (a == 4)
DoAnotherThing();
else
DoSomethingElse();
The reason that it is written as else if so commonly is because it compliments the logical flow of the code. That, and it just looks so much prettier.
Mostly it makes the code cleaner, easier to read, makes indenting better, particularly if you have any conventions on character length of rows (and if you don't then you've got thirty indents in a big if statement, such a pain to read). It also saves space, a few extra characters and indents across thousands of lines may not be much, but why use it if you don't have to. When the code compiles they will pretty much be the exact same in the DLLs anyways.
I've come across a situation like this a few times:
while (true) {
while (age == 5); //What does this semi-colon indicate?
//Code
//Code
//Code
}
The while(true) indicates that this is an infinite loop, but I have trouble understanding what the semi-colon after the while condition accomplishes, isn't it equivalent to this?:
while (age == 5) { }
//Code
//Code
In other words, does it mean that the while loop is useless as it never enters the block?
while (age == 5); // empty statement
is equivalent to
while (age == 5) { } // empty block
Update: Even if there is no body to execute, doesn't mean that the loop terminates. Instead it will simply loop repeatedly over the conditional (which may have or rely upon side-effects) until it is satisfied. Here is the equivalent form with a goto:
loop:
if (age == 5)
goto loop;
This construct is sometimes used as a busy-loop waiting on a flag to be changed in threaded code. (The exact use and validity varies a good bit by language, algorithm, and execution environment.)
I find the use of ; for an "empty block" empty statement a questionable construct to use because of issues like this:
while (age == 5); {
Console.WriteLine("I hate debugging");
}
(I have seen this bug several times before, when new code was added.)
Happy coding.
while (age == 5); gets stuck into an infinite loop. In c ; is a null terminator. The compiler assumes that the above loop has only one statement that is ; which causes the loop to be iterated over infinitely.
a statement consisting of only
;
is a null statement. It is the same as a block (also called compound statement) with nothing inside
{
}
They both perform no operations.
If we put ; anywhere it means null statement (statement that does nothing).
When we write
while(true);
It means a while loop an a statement that does nothing. It is similar to the
while(true)
i++;
Here statement is not null but in the previous case statement was null.
What is difference between these two examples:
if(firstchek)
{
if(second)
{
return here();
}
else
{
return here();
}
}
and this:
if(firstcheck)
{
if(second)
{
return here();
}
return here();
// else code without else
}
// code without else
// else code is here
return here();
This code:
if (someCondition)
{
foo();
return;
}
bar();
return;
is the same as this:
if (someCondition)
{
foo();
}
else
{
bar();
}
return;
The only difference is in readability. Sometimes one way is more readable, sometimes the other. See Refactoring: Replace Nested Conditional with Guard Clauses.
Nested conditionals:
double getPayAmount() {
double result;
if (_isDead) result = deadAmount();
else {
if (_isSeparated) result = separatedAmount();
else {
if (_isRetired) result = retiredAmount();
else result = normalPayAmount();
};
}
return result;
};
Guard clauses:
double getPayAmount() {
if (_isDead) return deadAmount();
if (_isSeparated) return separatedAmount();
if (_isRetired) return retiredAmount();
return normalPayAmount();
};
Assuming there is no other code, there is no difference in terms of code paths and what gets executed.
The main difference, in general, is that when specifying an else clause, this will only run if the expression in the if evaluates to false. If you do not specify it, the code will always run.
Update:
This:
if(second)
{
return here();
}
else
{
return here();
}
And this:
if(second)
{
return here();
}
return here();
Would be the same as this:
return here();
Why? Because you are doing the same thing regardless of what second evaluates to, so the check is superfluous.
The two sets of code are semantically similar. That is to say they will perform the same at run time. However, Whether you should use one form or another depends on the situation. Your code should express your intent in addition to the required semantics.
If the intent of the code is to do one or the other then keep the else so your intent is explicit. E.g.
if (withdrawAmmount < accountBalance)
{
return Deduct();
}
else
{
return ArrangeCredit();
}
If however the intent is to do the first thing in a special case then feel free to omit the else. E.g.
if (parameter == null)
{
return NothingToDo();
}
return PerformActions();
For maintainability you should consider whether removing the return statements will change the behaviour and code on the basis that some idiot will do that (it could be me).
It should also be noted that with the else the code performs the same without the returns but without the returns omitting the else will cause the code to behave differently.
With the first code you are running something regardless if second is a defined value or not. It just depends on whether it is a defined value or not. If it is you run one bit of code. If it isn't then you run another. With the second example you will only run code if second is a defined value.
In the first case, the else part is only executed if the second variable is false.
In the second case, the part where the else is left out is always executed (given that firstcheck is true in both cases).
Your code has too many return statements that i feel as repetitive for example
if(firstchek)
{
if(second)
{
return here();
}
else
{
return here();
}
}
the above is equal to
if(firstchek)
{
return here();
}
because here() is the same function call. And the second example
if(firstcheck)
{
if(second)
{
return here();
}
return here();
// else code without else
}
// code without else
// else code is here
return here();
is equal to
if(firstcheck)
{
return here();
}
return here();
In the first example if there are some statement after the example and the top level if condition fails then the statements following it will be executed example
if(firstchek)
{
if(second)
{
return here();
}
else
{
return here();
}
}
CallMyCellNo();
CallMyCellNo() will be called if the toplevel if condition fails.
In the second example you have return here() after the toplevel if statement so regardless of the if condition's return value the function execution will terminate.