I sometimes use
if (this._currentToolForeColor.HasValue)
return this._currentToolForeColor.Value;
else
throw new InvalidOperationException();
other times I use
if (this._currentToolForeColor.HasValue)
return this._currentToolForeColor.Value;
throw new InvalidOperationException();
The two are equivalent, I know, but I am not sure which is the best and why.
This goes even further as you can use other execution-control statements such as brake or continue :
while(something)
{
if(condition)
{
DoThis();
continue;
}
else
break;
}
versus
while(something)
{
if(condition)
{
DoThis();
continue;
}
break;
}
EDIT 1 : Yes the loop example(s) suck because they are synthetic (i.e.: made up for this question) unlike the first which is practical.
Fail early.
Do your validation at the top of the method, and if you get past it, you can use the values in (relative) safety.
public void SomeFunction(object someParameter)
{
if (someParameter == null) throw new ArgumentNullException("someParameter", "Value cannot be null");
// Use the parameter here for stuff
SomeOtherFunction(someParameter, Whichway.Up);
}
The same goes for the return statement. If your method is done, don't wrap stuff in big if statements, just return and get out of there.
See reducing cyclomatic complexity for other examples of this concept. Notice in my example there is only one code path, it's just a matter of how far along you can get with given parameters. Nested ifs and braces (even if you don't use the braces, as in your example) all have a greater impact on readability than the difference between your examples.
First and second options are equivalent to the compiler. But to a human reading the code, the first option is definitely more clear about the intent, and easier to read.
There are limits to what a human reader can absorb from thousands of lines of text designed primarily to function, not to convey meaning. Every tiny effort that makes the task easier is good.
while(something) {
if(condition)
{
DoThis();
continue;
}
else
break; }
Is the same as the following:
while(something && condition)
{
DoThis();
}
To your question: It is always better to be more explicit how the control flows even if it looks redundant (e.g. superfluous else connections are optimized away anyway). So if (cond) return x else throw y is good.
But in case of of error checking for method arguments you should do all checks at the start of the method, so you don't need any else's here.
I guess that depends on your preferences. I personally prefer the first options since it is less verbose. Luckily Resharper and I agree on this, so it is easy to let R# change the code for the shorter version.
I think in this case readibility is the main concern.
If you find yourself scrolling up ad down in the same method, or losing track of execution flow, it should probably be rewritten. break in the above indicates to me that the while condition was not sufficiant check.
It has its uses, but be careful, you dont want some coment appearing from another developer in the team saying
THERE BE DRAGONS HERE!!!
Resharper will recommend that you use this:
if( someCondition )
return foo;
throw new InvalidArgumentException();
But, does that mean that it is therefore better ? I don't know.
Personally, I find the following solution more explicit, and therefore I like it more. But that is just a personal choice.
if( someConditiion )
{
return foo;
}
else
{
throw new ....
}
Regarding your 'while' examples. IMHO, both your code examples suck.
Why not write it like this:
while( something )
{
if( !condition )
break;
DoStuff();
}
For a better and cleaner code, I think it is better to choose always this form:
if(condition)
{
//do stuff
}
else
{
//do stuff
}
..and so on.
It's just a matter of "taste", but even if you have more rows of code, this is clearly readable, because you don't have to interpret nor understand, you can follow the code flow with your finger easily. So, for me, always the else even if a return prevents fallback into following code, always brackets event if you have a one-row if/else and so on.
As far as I can remember, this is also suggested in Framework Design Guidelines, very easy book with lot of "do this" and "don't do this" guidelines.
Related
This question already has answers here:
Breaking out of a nested loop
(26 answers)
Closed 6 years ago.
how to break first for each loop from second nested for each loop in c#,I want to check some conditions in the second for each loop then try to break the parent for each loop
foreach(//do some stuff)
{
foreach(//do some stuff)
{
if(//check some condition)
{
break;//but want to break first foreach loop
}
}
}
Quick answer:
foreach(//do some stuff)
{
foreach(//do some stuff)
{
if(//check some condition)
{
goto end; // I'd probably add a comment here
}
}
// *1
}
end:
{} // the rest of your code.
But, but SESE...
SESE violations are violations of the Single Entry Single Exit principle. It's quite easy to fix, by using an extra condition:
bool found = false;
for (int i=0; i<foo.Count && !found; ++i)
{
for (int j=0; j<bar.Count; ++j)
{
if (...) { found = true; }
}
// *1
if (!found) { ... }
}
So why use a GOTO here?
I believe that creating proper, maintainable code means that you use the language constructs that most closely describes your intent. "Code" here is always composed of two things:
Control flow, which is expressed through things like for, while, break and goto.
Data flow, which is expressed through expressions, variables, and other memory access.
The intent of the OP is to break out of a nested loop, which is the equivalent of a control flow operation. I therefore believe you should use the control flow operation that most closely represents what the intent is - which is in this case a goto.
Note that this is not at all a reason you should abuse for introducing goto statements all over the place; if you do, the code will become very hard to read, which has nothing to do with maintainability and readability. You should consider the goto statement as a 'last resort control flow' statement, which is very rarely used in properly crafted code.
That said, in this case, this means that you shouldn't create local variables to handle control flow, unless that's absolutely necessary (e.g. if there's no language construct available that can express your intent clearly). For the same reason, I wouldn't have used Linq in this particular scenario.
I want performance. What should I do?
I believe most abuse of language constructs results from not understanding how the compiler deals with code, which is why I make it a habit of explaining parts of how it works internally. Please keep in mind that I recommend using a goto because it most clearly describes your intent, not because it might be a bit faster. Here goes:
Imagine being the compiler. You have a ton of code at the point of *1 in your code and cannot use return. Now there's two options:
You can use a goto.
You can use the extra flag.
Option 1 will compile to a field, which has memory. Memory is 'scarse' in the sense that compilers will do their best to consume as little memory as possible, preferable in registers. That's where your performance originates from. So, the compiler will attempt to eliminate the flag.
To do this, your compiler will do a ton of flow analysis and other stuff, in an attempt to determine that there are actually two code paths: the one is when the flag is set and the other one if it's not.
Now, if you're lucky the compiler will have its 'aha' moment and change your code from (2) to a simple GOTO, in which case the sky is still blue and everyone is happy.
However, if you're not lucky (and there are a ton of practical reasons for this to happen), it will not detect this from flow analysis and won't create the GOTO. Since your flag is used in the inner loop, it might even allocate a register for this, which might be the worst case scenario.
If you would have used the goto in the first place, there's no need for all this. You simply give the compiler the right solution. Simple.
Hrm do you have more details about how the compiler does this?
Yes, look at this 2 hour video of Chandler that explains a lot on how compilers work: https://www.youtube.com/watch?v=FnGCDLhaxKU
-updated- Apparently some people misintepreted my story as was pointed out by #Groo. I've made some adjustments to clarify what I meant to say.
You could do so by using a 'flag'
bool breakout = false
foreach(//do some stuff)
{
foreach(//do some stuff)
{
if(//check some condition)
{
breakout = true;
break;
}
}
if(breakout)
break;
}
If you can't return, I suggest using Linq, it makes your code readable:
Boolean found = false;
foreach(var item1 in source1.TakeWhile(_ => !found)) {
foreach(var item2 in source2.TakeWhile(_ => !found)) {
if (some condition)
{
found = true;
//break; // Not necessary
}
}
}
You can try to use return like this:
foreach(//do some stuff)
foreach(//do some stuff)
if(//check some condition)
return;
You can use WHILE. Maybe this code helps to you
foreach(// Some condition here)
{
//solution
bool breakme = false;
while (// Some condition here)
{
foreach (// Some condition here)
{
if (// Condition again)
{
//Do some code
}
if (// Condition again)
{
//Stop the first foreach then go back to first foreach
breakme = true;
break;
}
}
}
if(breakme)
{
break;
}
}
bool doBreak = false;
foreach(//do some stuff)
{
foreach(//do some stuff)
{
doBreak = <check some condition>;
if(doBreak) break;
}
if(doBreak) break;
}
I have this code that we can write in two ways
First Way
void func(int val)
{
if(val == 0)
return;
// Do something ...
}
Second Way
void func(int val)
{
if(val != 0)
{
// Do something ...
}
}
The Question:
Is there any reason to use the first way ?
Is there any Advantage to use the first way ( in C++ or in C# )
The main reason to use the first way is to reduce nesting in your source file.
See Invert “if” statement to reduce nesting.
Basically this becomes important when '// Do something ...' is a lot of code.
Imagine, that there's more than one condition, and look at this:
if (...)
{
if (...)
{
if (...)
{
if (...)
{
if (...)
{
...
}
}
}
}
}
and this:
if (!...)
return;
if (!...)
return;
if (!...)
return;
if (!...)
return;
if (!...)
...
I think, the second one is more readable an convenient.
If there's one or two conditions, the difference is insignificant.
Yes there are advantages as mentioned in previous answers. Since it is tagged in C++ care should be taken for freeing the allocated memory in case of using First Way.
For Eg there can be bad code like this
void func(int val)
{
Foo *obj = new Foo();
if(val == 0)
return;
// Do something ...
delete obj; // Possible Memory leak
}
There is no difference - whether to use one or the other depends entirely on your subjective preference for one or the other, influenced by readability, understandability, etc
if you want to exit quick on a defined value, so return before should be better,
but if this case is rare, so probably it's better to directly work on good data.
depending on which language you use, implications on performance should be greater, or insignificant.
if it's intended for clarity, so make some functions called after conditions should be good.
Some parts manage different cases, some parts process it.
maintainability and readability should be improved this way.
if you call as the first way then its not run the rest of the things. because it return directly. but if you use second way the codes inside the will run.
Void methods do not require a return statement always. But you can use a 'return' in a strategic place to avoid executing unnecessary statements when you have encountered an exit condition.
Imagine the following code:
void DoThis()
{
if (!isValid) return;
DoThat();
}
void DoThat() {
Console.WriteLine("DoThat()");
}
Is it OK to use a return inside a void method? Does it have any performance penalty? Or it would be better to write a code like this:
void DoThis()
{
if (isValid)
{
DoThat();
}
}
A return in a void method is not bad, is a common practice to invert if statements to reduce nesting.
And having less nesting on your methods improves code readability and maintainability.
Actually if you have a void method without any return statement, the compiler will always generate a ret instruction at the end of it.
There is another great reason for using guards (as opposed to nested code): If another programmer adds code to your function, they are working in a safer environment.
Consider:
void MyFunc(object obj)
{
if (obj != null)
{
obj.DoSomething();
}
}
versus:
void MyFunc(object obj)
{
if (obj == null)
return;
obj.DoSomething();
}
Now, imagine another programmer adds the line: obj.DoSomethingElse();
void MyFunc(object obj)
{
if (obj != null)
{
obj.DoSomething();
}
obj.DoSomethingElse();
}
void MyFunc(object obj)
{
if (obj == null)
return;
obj.DoSomething();
obj.DoSomethingElse();
}
Obviously this is a simplistic case, but the programmer has added a crash to the program in the first (nested code) instance. In the second example (early-exit with guards), once you get past the guard, your code is safe from unintentional use of a null reference.
Sure, a great programmer doesn't make mistakes like this (often). But prevention is better than cure - we can write the code in a way that eliminates this potential source of errors entirely. Nesting adds complexity, so best practices recommend refactoring code to reduce nesting.
Bad practice??? No way. In fact, it is always better to handle validations by returning from the method at the earliest if validations fail. Else it would result in huge amount of nested ifs & elses. Terminating early improves code readability.
Also check the responses on a similar question: Should I use return/continue statement instead of if-else?
It's not bad practice (for all reasons already stated). However, the more returns you have in a method, the more likely it should be split into smaller logical methods.
The first example is using a guard statement. From Wikipedia:
In computer programming, a guard is a
boolean expression that must evaluate
to true if the program execution is to
continue in the branch in question.
I think having a bunch of guards at the top of a method is a perfectly understandable way to program. It is basically saying "do not execute this method if any of these are true".
So in general it would like this:
void DoThis()
{
if (guard1) return;
if (guard2) return;
...
if (guardN) return;
DoThat();
}
I think that's a lot more readable then:
void DoThis()
{
if (guard1 && guard2 && guard3)
{
DoThat();
}
}
There is no performance penalty, however the second piece of code is more readable and hence easier to maintain.
In this case, your second example is better code, but that has nothing to do with returning from a void function, it's simply because the second code is more direct. But returning from a void function is entirely fine.
It's perfectly okay and no 'performance penalty', but never ever write an 'if' statement without brackets.
Always
if( foo ){
return;
}
It's way more readable; and you'll never accidentally assume that some parts of the code are within that statement when they're not.
I'm going to disagree with all you young whippersnappers on this one.
Using return in the middle of a method, void or otherwise, is very bad practice, for reasons that were articulated quite clearly, nearly forty years ago, by the late Edsger W. Dijkstra, starting in the well-known "GOTO Statement Considered Harmful", and continuing in "Structured Programming", by Dahl, Dijkstra, and Hoare.
The basic rule is that every control structure, and every module, should have exactly one entry and one exit. An explicit return in the middle of the module breaks that rule, and makes it much harder to reason about the state of the program, which in turn makes it much harder to say whether the program is correct or not (which is a much stronger property than "whether it appears to work or not").
"GOTO Statement Considered Harmful" and "Structured Programming" kicked off the "Structured Programming" revolution of the 1970s. Those two pieces are the reasons we have if-then-else, while-do, and other explicit control constructs today, and why GOTO statements in high-level languages are on the Endangered Species list. (My personal opinion is that they need to be on the Extinct Species list.)
It is worth noting that the Message Flow Modulator, the first piece of military software that EVER passed acceptance testing on the first try, with no deviations, waivers, or "yeah, but" verbiage, was written in a language that did not even have a GOTO statement.
It is also worth mentioning that Nicklaus Wirth changed the semantics of the RETURN statement in Oberon-07, the latest version of the Oberon programming language, making it a trailing piece of the declaration of a typed procedure (i.e., function), rather than an executable statement in the body of the function. His explication of the change said that he did it precisely because the previous form WAS a violation of the one-exit principle of Structured Programming.
While using guards, make sure you follow certain guidelines to not confuse readers.
the function does one thing
guards are only introduced as the first logic in the function
the unnested part contains the function's core intent
Example
// guards point you to the core intent
void Remove(RayCastResult rayHit){
if(rayHit== RayCastResult.Empty)
return
;
rayHit.Collider.Parent.Remove();
}
// no guards needed: function split into multiple cases
int WonOrLostMoney(int flaw)=>
flaw==0 ? 100 :
flaw<10 ? 30 :
flaw<20 ? 0 :
-20
;
Throw exception instead of returning nothing when object is null etc.
Your method expects object to be not null and is not the case so you should throw exception and let caller handle that.
But early return is not bad practice otherwise.
During code review I discovered many places of our C# code that looks like this:
if(IsValid()) {
return true;
}
else {
return false;
}
or even "better":
return (IsValid()? true : false);
I always wondered why not just write the code like this:
return IsValid();
This is the way I would write this code. I ain't questioning the skills of the developers, but maybe trying to look into the developer's soul. Why would a developer favor more complex code and not a more simple and intuitive? Or maybe the reason is that it is hard to accept the Boolean type as the first-class citizen?
I think return IsValid(); is perfectly valid and readable code.
BTW, I would certainly slap anyone who writes (IsValid() ? true : false) in the face. It's unnecessarily complicated.
PS. This is what svn blame is designed for.
Yes, you should do it as you say. These people are doing these overly verbose things because they first learned it that way, perhaps in CS 101, and it never occurs to them to go outside the space of what they know works to see if there is a better, easier way.
This does speak to their competence. Good programmers need to be a little more thoughtful and a lot less hidebound.
The reasons for the first two examples are entirely human:
ignorance
lack of intellectual involvement with one's code
code was refactored, but only half-way
There's no reason not to (I know it's a double negative) go with return IsValid();
If you're absent-minded, it's easy to refactor some code from this:
private bool ConsiderTheOstrich()
{
/* do ostrich things */
if(someCondition && unpredictableThing == 5)
return true;
else
{
// log something
return false;
}
}
To this:
private void IsValid() { return (someCondition && unpredictableThing == 5); }
/* ... */
private void ConsiderTheOstrich()
{
/* do ostrich things */
if(IsValid())
return true;
else
return false; // ostrichlogger logs it for us now
}
Without noticing the extra opportunity for brevity.
First case is easier when you are debugging. When you step through your source, it is easier to find out what the return value is without opening up immediate window or run IsValid(); just to see the return value.
For the first and second case, developer might not be aware that s/he can simply do
return IsValid();
Lastly, a developer might be forced to use first or second syntax due to company policies.
I would also just say "return IsValid();" I think you're 100% correct in doing so
return IsValid(); is the way to go. less code, more concise - choice of champions
I even sometimes see this some of the legacy code I maintain:
bool retValue;
if (IsValid())
{
retValue = true;
}
else
{
retValue = false;
}
return retValue;
Are some programmers paid by the character?
Yes, of course return IsValid(); would be most optimal if the only code you have is as above.
I guess what comes into play though is what else is your function doing? The rest of the code might shed more light on why a developer would put an if statement around IsValid().
After all, if it's just returning IsValid() then why isn't the calling code just checking IsValid() directly rather than having this wrapper method.
Distraction
I know it's occurred in my code before and I can trace that back to when I was interrupted or not paying attention while coding (I solely blame SO!)
Ignorance
Not knowing the better way to do it. We take it for granted that all programmers think logically, but that's not the case. Some coders are going purely on patterns of what they've seen before:
If (integerA == integerB) { //do special stuff }
//Given integer equality; boolean equality ought to look the same...
If (isValid() == true ) { //do special stuff }
Momentum
That's how someone has always done it and therefore that's how they continue to do it.
I have a couple of methods that return a bool depending on their success, is there anything wrong with calling those methods inside of the IF() ?
//&& makes sure that Method2() will only get called if Method1() returned true, use & to call both methods
if(Method1() && Method2())
{
// do stuff if both methods returned TRUE
}
Method2() doesn't need to fire if Method1() returns FALSE.
Let me know there's any problem with the code above.
thank you.
EDIT: since there was nothing wrong with the code, I'll accept the most informative answer ... added the comment to solve the "newbie & &&" issue
I'll throw in that you can use the & operator (as opposed to &&) to guarantee that both methods are called even if the left-hand side is false, if for some reason in the future you wish to avoid short-circuiting.
The inverse works for the | operator, where even if the left-hand condition evaluates to true, the right-hand condition will be evaluated as well.
No, there is nothing wrong with method calls in the if condition. Actually, that can be a great way to make your code more readable!
For instance, it's a lot cleaner to write:
private bool AllActive()
{
return x.IsActive && y.IsActive && z.IsActive;
}
if(AllActive())
{
//do stuff
}
than:
if(x.IsActive && y.IsActive && z.IsActive)
{
//do stuff
}
As useful as they are, sequence points can be confusing. Unless you really understand that, it is not clear that Method2() might not get called at all. If on the other hand you needed BOTH methods to be called AND they had to return true, what would you write? You could go with
bool result1 = Method1();
bool result2 = Method2();
if (result1 && result2)
{
}
or you could go with
if (Method1())
if (Method2())
{
}
So I guess the answer to you question IMHO is, no, it's not exactly clear what you mean even though the behavior will be what you describe.
I would only recommend it if the methods are pure (side-effect-free) functions.
While, as everyone says, there's nothing "wrong" with doing things this way, and in many cases you're doing precisely what the language was designed for.
Bear in mind, however, that for maintainabilities sake, if Method2 has side effects (that is, it changes somethings state) it may not be obvious that this function is not being called (a good programmer will usually know, but even good programmers sometimes have brain farts).
If the short circuited expression has some kind of side effect, it may be more readable to seperate the statements, strictly from a maintenance perspective.
Looks good to me, multiple clauses in the if() block will short circuit if an earlier condition fails.
There shouldn't be any problem.
The normal behavior is that Method1() will execute, and if that returns true Method2() will execute, and depending on what Method2() returns, you may / may not enter the if() statement.
Now, this assumes that the compiler generates code that executes that way. If you want to be absolutely sure that Method2() doesn't execute unless Method1() returns true you could write it like this
if( Method1() )
{
if( Method2() )
{
// do stuff if both methods returned TRUE
}
}
But, I've always observed that your code will run as expected, so this is probably not necessary.
Nothin' wrong.
Actually...I wouldn't name them Method1 and Method2. Something more descriptive. Maybe passive sounding too (like StuffHasHappened or DataHasLoaded)
Looks good to me, but there are some caveats... This is NOT the kind of thing where blanket rules apply.
My guidelines are:
If the method names are short, and there are not too many of them, then it's all good.
If you have too many statements/method calls inside the if statement, you most likely are comparing more than one "set" of things. Break those "sets" out and introduce temporary variables.
"Too many" is subjective, but usually more than around 3
When I say "method names are short" I'm talking not just about the names, but the parameters they take as well. Basically the effort required for someone to read it. For example if( Open(host) ) is shorter than if( WeCouldConnectToTheServer ). The total size of all these items is what it comes down to.
Personally, I would consider
if(Method1() && Method2())
{
// do stuff if both methods returned TRUE
}
to be a bad practice. Yes, it works in the current environment, but so does
if(Method1())
{
if (Method2())
{
// do stuff if both methods returned TRUE
}
}
But will it work in ALL environments? Will future, possibly non-Microsoft, C# compilers work this way? What if your next job involves another language where both methods will always be called? I wouldn't rely on that particular construct not because it's wrong, but because it doesn't solve any serious problem, and it may become wrong in the future