chain up multiple IFs - evaluate next only if current is false - c#

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);

Related

Undesired conditions hit when checking for list equality

Currently facing a rather.. trivial issue.
I have two error-handling conditions:
1. Triggers true if two lists are inequal.
For example:
2. Triggers true if the cachedList.Length is > than the newList.Length.
For example:
First method to check string equality is this:
if (!checkEquality(cachedList, newList))
{
// do something
}
Where checkEquality() is:
public bool checkEquality(List<string> cachedList, List<string> newList)
{
if (cachedList.SequenceEqual(newList))
{
return true;
}
else {
return false;
}
}
The second method I use is:
if (cachedList.Count > newList.Count)
{
// Do something
}
With this said, and understandingly, when a scenario where condition no. 2 is hit, where the cached list is greater than the new list, both my conditions get hit. Both the "inequal" and "greater than" condition is hit, and it's causing undesired behavior in my code.
In order to not satisfy both these conditions when error-handling number 2 is hit, I need to think of an alternative to detect "inequality" in method number 1.
EDIT: I decided to put in a condition to check if the counts of newList and cachedList are equal, and only check for their equality given their count is equal. Is this the right way to approach this?
public bool checkEquality(List<string> oldFirstList, List<string> newFirstList)
{
if (oldFirstList.Count == newFirstList.Count)
{
if (oldFirstList.SequenceEqual(newFirstList))
{
return true;
}
else
{
return false;
}
}
return true;
}
The second problem it´s right the cachedList.Count > newList.Count, and that´s the reason why the if is true.
if (cachedList.Count > newList.Count)
{
// Do something
}
This will "do something" because it´s true the condition
And your first problem, try something like this:
Instead of this:
if (!checkEquality(cachedList, newList))
{
// do something
}
Try this directly:
if (cachedList.SequenceEqual(newList))
{
return true;
}
else
{
return false;
}
This will return false;
According to the documentation for SequenceEqual, the length check is already being done there. Unless you have no other criteria other than length and equality, there is no need to wrap SequenceEqual into your own method. You can even define a type of IEqualityComparer<T> if you want to compare more than references.

Resharper redundant 'else' really redundant?

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.

Replacing If Else unique conditional nested statements

Switch case statements are good to replace nested if statements if we have the same condition but different criteria. But what is a good approach if those nested if statements all have different and unique conditions? Do I have any alternate options to replace a dozen if else statements nested inside each other?
Sample Code:
Note: I know this is extremely unreadable - which is the whole point.
Note: All conditions are unique.
...
if (condition) {
// do A
} else {
if (condition) {
// do B
if (condition) {
if (condition) {
if (condition) {
// do C
if (condition) {
// do D
if (condition) {
// do E
} else {
if (condition) {
// do F
}
}
}
}
if (condition) {
// do G
if (condition) {
// do H
if (condition) {
// do I
} else {
// do J
}
}
}
}
}
}
​
The best approach in this case is to chop up the thing into appropriately named separate methods.
I had to check this was Stackoverflow not DailyWTF when I saw the code!!
The solution is to change the architecture and use interfaces and polymorphism to get around all the conditions. However that maybe a huge job and out of the scope of an acceptable answer, so I will recommend another way you can kinda use Switch statements with unique conditions:
[Flags]
public enum FilterFlagEnum
{
None = 0,
Condition1 = 1,
Condition2 = 2,
Condition3 = 4,
Condition4 = 8,
Condition5 = 16,
Condition6 = 32,
Condition7 = 64
};
public void foo(FilterFlagEnum filterFlags = 0)
{
if ((filterFlags & FilterFlagEnum.Condition1) == FilterFlagEnum.Condition1)
{
//do this
}
if ((filterFlags & FilterFlagEnum.Condition2) == FilterFlagEnum.Condition2)
{
//do this
}
}
foo(FilterFlagEnum.Condition1 | FilterFlagEnum.Condition2);
#Tar suggested one way of looking at it. Another might be.
Invert it.
if (myObject.HasThing1)
{
if(myObject.HasThing2)
{
DoThing1();
}
else
{
DoThing2();
}
}
else
{
DoThing3();
}
could be
DoThing1(myObject.HasThing1);
DoThing2(myObject.HasThing2);
DoThing3(myObject.HasThing3);
So each Do method makes the minimum number of tests, if any fail the it does nothing.
You can make it a bit cleverer if you want to break out of the sequence in few ways.
No idea whether it would work for you, but delegating the testing of the conditions is often enough of a new way of looking at things, that some simplifying factor might just appear as if by magic.
In my point of view there exists two main methods to eliminate nested conditions. The first one is used in more special cases when we have only one condition in each nested conditions like here:
function A(){
if (condition1){
if (condition2){
if (condition3){
// do something
}
}
}
}
we can just go out from the opposite condition with return:
function A(){
if (condition1 == false) return;
if (condition2 == false) return;
if (condition3 == false) return;
// do something
}
The second one is using a condition decomposition and can be treated as more universal than the first one. In the case when we have a condition structure like this, for example:
if (condition1)
{
// do this 1
}
else
{
if (condition2)
{
// do this 2
}
}
We can implement a variables for each particular condition like here:
bool Cond1 = condition1;
bool Cond2 = !condition1 && condition2;
if (Cond1) { //do this 1 }
if (Cond2) { //do this 2 }
If that really is the business logic then the syntax is OK. But I have never seen business logic that complex. Draw up a flow chart and see if that cannot be simplified.
if (condition)
{
// do this
}
else
{
if (condition)
{
// do this
}
}
can be replaced with
if (condition)
{
// do this
}
else if (condition)
{
// do this
}
But again step back and review the design. Need more than just an else if clean up.
I feel your pain.
My situation required writing many (>2000) functional tests that have been customer specified for a large, expensive piece of equipment. While most (>95%) of these tests are simple and have a straight forward pass/fail check dozens fall into the "multiple nested if this do that else do something different" at depths similar or worse than yours.
The solution I came up with was to host Windows Workflow within my test application.
All complex tests became Workflows that I run with the results reported back to my test app.
The customer was happy because they had the ability to:
Verify the test logic (hard for non programmers looking at deeply nested if/else C# - easy looking at a graphical flowchart)
Edit tests graphically
Add new tests
Hosting Windows Workflow (in .NET 4/4.5) is very easy - although it may take you a while to get your head around "communications" between the Workflows and your code - mostly because there are multiple ways to do it.
Good Luck

stop iterating after returning a true?

(couldn't think of a better title, feel free to edit it to a title that describes the question better)
I have the following method:
bool CalculateNewState(int adjacent, bool currentState)
{
if (currentState == true)
{
foreach (int n in liveRule)
{
if (adjacent == n)
{
return true;
}
}
return false;
}
else
{
foreach (int n in becomeAliveRule)
{
if (adjacent == n)
{
return true;
}
}
return false;
}
}
This is for a game of life clone. What I want to implement is that a user can make his own rules.
The bool currentState tells the method whether the cell is alive or not. the int adjacent tells the method how many alive neighbors the cell has.
What I want to achieve with this is that when the user says:
2,3 and 5 neighbors keep the cell alive. That it will iterate through an array (liveRule) that holds 2,3 and 5. when any match occurs it should return true, else false.
What happens here is that, after returning a true, it keeps iterating and will eventually return whether the last element in liveRule matched.
What do I need to do, to stop iterating after a match has occurred?
It is of course possible I'm taking the wrong approach to this problem. I started from the suggestions here.
(tried to describe it to the best of my abilities, but it still seems quite unclear)
This is C# in Unity3D.
The code you've implemented says "if adjacent is unequal to any of 2, 3 or 5, then return". Obviously adjacent cannot be equal to all of them!
Start over. Rename your methods so that they are more clear. Booleans should answer a true/false question, so choose names that ask a question:
bool IsCellAlive(int adjacentCount, bool isAlive)
{
if (isAlive)
return liveRule.Contains(adjacentCount);
else
return deadRule.Contains(adjacentCount);
}
"Contains" is slower than a foreach loop, so this might cause a performance problem. Don't worry about it for now; you haven't even got the code correct yet. Write the code so that it is obviously correct, and then use a profiler to find the slow spot if it is not fast enough.
Remember: make it correct, then make it clear, then make it fast.
Your return statements will exit the CalculateNewState method immediately. If you find that the iteration is continuing, either you are not hitting the return statements (adjacent == n is never true), or possibly CalculateNewState is being called repeatedly from elsewhere in your code.
You can probably rewrite it much more simply to something like:
if (currentState)
return liveRule.Contains(adjacent);
return becomeAliveRule.Contains(adjacent);
Well you can always use a "break" statement to terminate the loop. Do something like:
bool CalculateNewState(int adjacent, bool currentState)
{
if(currentState)
{
return IsStateMatch(adjacent, liveRule);
}
else
{
return IsStateMatch(adjacent, becomeAliveRule);
}
}
bool IsStateMatch(int adjacent, int[] rules)
{
bool finalState = false;
if(rules != null)
{
for(int i = 0; i < rules.length; i++)
{
if(adjacent == rules[i])
{
finalState = true;
break;
}
}
}
return finalState;
}
I broke down the methods a little more, just for readability, but I think this is the basic idea. Now, I do agree with the other posters about what could be happening. If your loop is continuing after a break / return statement, then you most likely have buggy code elsewhere incorrectly calling the method.
It looks like your equality test is the culprit... shouldn't you be testing adjacent == n instead of adjacent != n? That way it will return true for the matches and only return false if no match.
The iterator will NOT continue after a return exits the loop.
Can you use a for loop instead of foreach with an additional variable?
bool CalculateNewState(int adjacent, bool currentState)
{
if (currentState == true)
{
bool match = false;
for(int n = 0; n < liveRule.length && !match; n++)
{
if (adjacent != n)
{
match = true;
}
}
return match;
}
else
{
bool match = false;
for(int n = 0; n < becomeAliveRule.length && !match; n++)
{
if (adjacent != n)
{
match = true;
}
}
return match;
}
}

What is difference if I don't use the else condition

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.

Categories