When to use 'if…else if' and when to use - c#

1) I know how if…else if statements work, but in the next example both methods are identical as far as the resulting value is concerned. So does it matter which of the two methods I use or should I always go for one that is semantically closest to what the code is trying to do ( here I’m guessing that semantically the two methods are quite different )? So which method would you use and why?
protected string GetNumberDescription(int value)
{
if (value >= veryBigNumber)
return veryBigNumberDescription;
else if (value >= bigNumber)
return bigNumberDescription;
else if (value >= smallNumber)
return smallNumberDescription;
else
return "";
}
protected string GetNumberDescription(int value)
{
if (value >= veryBigNumber)
return veryBigNumberDescription;
if (value >= bigNumber)
return bigNumberDescription;
if (value >= smallNumber)
return smallNumberDescription;
else
return "";
}
2) I noticed losts of code uses the following format when writting if ... else if statements:
if ...
else if ...
else ...
But isn't ( at least conceptually ) more correct way:
if ...
else
if ...
else ...

You should probably use the first. It's more accepted, and more logical. (You don't care about anything afterwards if this condition is true... indicate that in your code.)
It's generally more accepted, and more compact and readable, to use the first way (else if). Python even has a specific keyword for it (elif).

I personally would use
protected string GetNumberDescription(int value)
{
if (value >= veryBigNumber)
return veryBigNumberDescription;
if (value >= bigNumber)
return bigNumberDescription;
if (value >= smallNumber)
return smallNumberDescription;
return string.Empty;
}
It really all depends on what your function is doing. If its simple like this then keep it simple. If you might need to do something with the result before you return it then I'd use Egrunin's solution

protected string GetNumberDescription(int value)
{
string ret = "";
if (value >= veryBigNumber)
ret = veryBigNumberDescription;
else if (value >= bigNumber)
ret = bigNumberDescription;
else if (value >= smallNumber)
ret = smallNumberDescription;
return ret;
}
The question is already answered, but I added this because:
There are advantages to having a single exit from a function.
The same variable is being tested repeatedly, so the if/elseif is most appropriate.
Edited to add:
I'm usually a big fan of exiting a function early in cases like this:
if (conditionOne)
{
if (conditionTwo)
{
if (conditionThree)
{
interesting_stuff();
}
}
else
boring();
}
return;
I'm much happier seeing this:
if (!conditionOne)
return;
if (!conditionTwo)
{
boring();
return;
}
if (!conditionThree)
return;
interesting_stuff();
return;
But when there are exits at many different nesting levels, it's too easy to miss one as you're reading over the code.
Also, as mentioned in the comments: a single exit means only one place to put a breakpoint.

If the conditions are mutually exclusive then I think an else if pattern is best. It will be harder to accidentally break as the code evolves and becomes more complex, because your control flow more accurately represents the mutual exclusiveness of the logic.
Consider if someone re-factored your first example to be similar to egrunin's example such that there is only one return, but consider they forgot to add the "else" to each if:
protected string GetNumberDescription(int value)
{
string ret = "";
if (value >= veryBigNumber)
ret = veryBigNumberDescription;
if (value >= bigNumber)
ret = bigNumberDescription;
if (value >= smallNumber)
ret = smallNumberDescription;
// BUG: very big numbers still fall through to this last condition,
// because they meet all conditions
return ret;
}
They have just introduced a bug. They may not have realized that the returns were part of the logic being expressed. While the error is obvious here, in real life this code a couple years down the road could potentially become more complex, lengthy, and more difficult to read such that it's easier to make such a mistake.
Detecting Unexpected Bug
Additionally, if at least one condition must be met(i.e. should never return an empty string), then I'd throw an exception in the final else if you are assuming all cases should be handled. This would detect a bug in the code where the code fell through all the elses and did not find a matching condition. If you do not throw an exception, then the bug might cause strange behavior. How will the rest of the code handle the uninitialized empty string? Depends largely on the code at hand. The idea of throwing an exception is to cause a hard failure exactly where the bug is so that it can be easily identified and corrected, instead of allowing the application to continue running with an invalid return.
if (value >= smallNumber)
ret = smallNumberDescription;
else if(...)
ret = otherNumberDescription;
else
throw new InvalidOperationException($"No condition matched for value={value}");
return ret;
If paired with appropriate exception logging/notifications, then this would allow you to become aware of this bug and add a condition to handle unanticipated values. Not really necessary for very simple conditions, but very helpful in proactively finding and correcting bugs in this kind of code.

They are semantically identical. I doubt there is any difference in performance, so the choice is about style and readability. If you're curious, compile the above code into an assembly and use Reflector to see if there is any difference in the IL. My guess is there would be little difference if any.

It's mostly a matter of preference. when using return statements, you don't need the elses in my opinion, since it's clear that the function ends right there. It's all very situation and style dependent, so there is no clear 'best' way to do it.

I would suggest the former, as you are making a logical choice between four possibilities. You are grouping the decision in one if/else if block.
If you separate out the decisions like in your second function, they appear to not be connected at all. Clearly they are, as the value variable is repeated, but it might not necessarily be obvious.
Additionally, when you've got nothing to return, please return null, and not a blank string. In an application I maintain, it is still necessary to use if (value == null || value != "").

You want to use "else if" because that only will fire if the first "if" is not accepted. In your case the 3 if statements are okay, simply because if a latter "if" is correct, then the previous "if"s cannot be.
In a case where all of your if statements could be correct, you'd want to use else if.
For Example:
if (8<10) {
return 10;
}
if (8<9) {
return 9;
}
That's a very simplistic example, but you get the idea. You use "else if" when you want only one "if" statement to fire.

I would use the first option, as it shows in code the comparisons are "grouped" some. For 2 I think they end up in exactly the same IL code.
I always make sure the most common senario is first in the if..else statement, as that is best for performance.

The alternatives are pretty close semantically, so it doesn't matter that much. As suggested in some answers, putting the result in a string variable and return at the end might better represent what you are doing in the method.
Another alternative is to use the conditional operand, which gives you a less verbose code:
protected string GetNumberDescription(int value) {
return
value >= veryBigNumber ? veryBigNumberDescription :
value >= bigNumber ? bigNumberDescription :
value >= smallNumber ? smallNumberDescription :
String.Empty;
}

With the return statements, it really doesn't matter. I totally disagree with those who say the second is in any way worse, though. What makes it worse?
In response to your second question: you are quite right. In fact, not only are the two ways of formatting if/else if effectively the same; they actually are literally the same. C# does not enforce a particular formatting style, so these are all identical:
// This...
if (A())
return "Congrats!";
else if (B())
return "Not bad!";
else if (C())
return "Next time...";
else
return "Uh-oh.";
// ...is the same as this...
if (A())
return "Congrats!";
else
if (B())
return "Not bad!";
else
if (C())
return "Next time...";
else
return "Uh-oh.";
// ...which is the same as this...
if (A()) return "Congrats!"; else
if (B())
return "Not bad!";
else
{ if
(C())
return
"Next time...";else{
return "Oh-oh.";
}}

protected string GetNumberDescription(int value)
{
return new NumberDescriptor(value).toString();
}
All you need is to hide your logic.
Don't take this too serious, but...i would do it that way. I know, your question is not anserwed here, but there are already enough if/then/else examples in this topic.

1) The first one is more prevalent and in common practice. So it would be wise to stick to the standard practice.
2) Generally when we have more than one conditional statement, else if is used in the intermediate conditional outputs and else is used in the last conditional output. Moreover it might be more efficient as I believe it does not have to check the same condition everytime unlike the if-else-if-else... type.
Its more like a choice provided to you where you find your own out of many paths going to the same destination. But the choice that you hear or see often is the one that is popular because of experience of many users and experts.

I would say to use the first if the function is thought of as returning one of four possibilities, all of which are considered "successful". I would use the latter style if some returns denoted "failures". For example (toy example--throwing might be better for the error cases):
string get_suit_name(int suit)
{
string suit_names[4] = {"clubs", "diamonds", "hearts", "spades"};
if (0 > suit) /* Avoid LT sign */
return "Suit is improperly negative!";
if (suit >= 4)
return "Suit is too big!";
return suit_names[suit];
}

Well from my point of view it would be these priorities from highest to lowest.
Functionality / achieving the end goal
Reduction of cost in any scope/level
Readability
^^^^ note that many will dispute this on my list and call readability above reduction of cost, it really depends on your work envi. and the end goal but I find this the most common. But guess coming from a rookie that doesn't mean much huh :D
After that you it's pretty much peanuts. Same goes for ? : operator. If you are convinced it's more readable, go for it. Function wise it doesn't really matter. But if(){}else{} is significantly different from if(){}else if(){} So pick what's the optimum code (Highest wanted results minus unexpected results - 0.5* readability score ) pretty much what I'd go on.
Now seeing as the code does the same for you, a new attribute comes into play, will this code be edited at some later stage? And if so what would be best to go for then? Don't forget the future of the code, nor the comments, that a free bonus to pick along with it. You can even do both if you can't figure it out for the time and just comment the other but that does leave sloppy walls of text to be removed later on cleanup/release.

For the example provided, you don't need to worry about "if" statements if you're willing to sacrifice a ton of readability and possibly a little speed:
string [] descriptions = {"", smallNumberDescription, bigNumberDescription, veryBigNumberDescription};
protected string GetNumberDescription(int value)
{
int index = Convert.ToInt32(value >= smallNumber) + Convert.ToInt32(value >= bigNumber)
+ Convert.ToInt32(value >= veryBigNumber);
return descriptions[index];
}

In terms of performance, they may be the same depending on the compiler/interpreter. In my opinion the second one is better....much easier to debug.

Well, in your particular case, I would suggest this:
protected string GetNumberDescription(int value) {
if (value >= veryBigNumber)
return veryBigNumberDescription;
if (value >= bigNumber)
return bigNumberDescription;
if (value >= smallNumber)
return smallNumberDescription;
return "";
}
Since, you are returning from the function on any of the true condition, there is no need to use 'else if'. In your case, if any of the conditions become true, the code won't execute further.
Also, the last 'else' is not required, for the control will reach that point only when all the above conditions have been false.
It's all a matter of where you're using it, and how. The main motive is to maximize the readability of your code and make it as elegant and easy-to-understand as possible.
Many would prefer the first way since it indicates in your code that you don't care what happens as soon as a condition is satisfied.

Related

C# Check if contains various combination of substring

I want to check If my OCR result (a string) is either "No Edge" or "No Signal".
Problem is sometimes I would get N0 Edge, No Signa1, N0 signa1, No 5ignal, etc. The letter o, S, i and l can sometimes become digits or something else. Unfortunately there is nothing else I can do regarding the OCR.
Currently I am doing this:
ocrResult = ocrResult.ToLower();
if (ocrResult.Contains("edg") || ocrResult.Contains("gna"))
{
//no edge or no signal
}
else
{
//Not no edge or no signal
}
Can any of you please suggest a smarter approach?
There's a library called Simila which is designed for such scenarios:
In Simila you can have this:
// A similarity engine which accepts similar if similarity is more than 70%
var simila = new Simila() { Treshold = 0.7 };
if (simila.AreSimilar(ocrResult, "No Edge") || simila.AreSimilar(ocrResult, "No Signal"))
{
// ...
}
A simple documentation of Simila is available here:
https://github.com/mehrandvd/Simila/wiki
FYI, I'm working on it and it is still in beta version. Let me know if an early release helps you, so I can create an early beta release for you.
If what you are doing works just keep doing it, it's simple, easy to understand and scanning a 9 letter string twice isn't likely to cause performance issues unless you have really big data sets.
Just add a comment so that someone who looks at this code years from now know why you are looking for seemingly random substrings.
If this isn't working then what you are looking for is a "classification algorithm" (Wikipedia list's 79 of them) - but they can get complex and choosing the right one can be tricky so they truly an overkill if simple string comparison does the job.
Well the .lower is slower then a comparison that ignores the case. Certainly if u use it in a loop. So at first i recommend you do a comparison that ignores the case. For readability and maintainability i advice u refactor the comparison. And finally u should check if the string is empty or null, then u do not have to compare the string.
Example:
if (IsThereNoEdgeOrNoSignal(ocrResult))
{
//no edge or no signal
}
else
{
//Not no edge or no signal
}
private static bool IsThereNoEdgeOrNoSignal(string ocrResult)
{
if (string.IsNullOrEmpty(ocrResult))
return false;
return ocrResult.IndexOf("edg", StringComparison.CurrentCultureIgnoreCase) >= 0 || ocrResult.IndexOf("gna", StringComparison.CurrentCultureIgnoreCase) >= 0;
}
if it only stays to these two strings, then you should keep it this way, does it grows with more possibilities you should check it with a regular expression.
I hope this helps u.

Ternary vs Chained If-else-if (Performance)

I did the due-diligence to see if this has been asked before and didn't find anything identical but close, so here goes.
Say I have a chain of if-else-if statements.
foreach (value in valueList)
if (value == 120) {
w = true;
} else if (value == 140) {
x = true;
} else if (value == 160) {
y = true;
} else if (value == 180) {
z = true;
}
}
Is there any advantage of changing the else-if chain to ternary expressions such as:
foreach (value in valueList) {
w = (value == 120) ? true : false;
x = (value == 140) ? true : false;
y = (value == 160) ? true : false;
z = (value == 180) ? true : false;
}
My first inclination is no. Because of the for loop every assignment is made each time the loop happens. Whereas in the if-else-if chain, the assignment is made only once. But the comparisons are made more often (right?). Can anybody settle this for me?
I know a switch would easily defeat the both in terms of performance. Can I base this question on the assumption that using switch is not an option?
I guess another question inside this question would be what are the Big-O comparisons between the two?
Note that both solutions are very different. The first one only assigns true to one of those four variables while the other one will overwrite whatever value all four of them had before.
That being said, using the ternary operator in the second code is really bad. You can just assign the result of the comparison directly:
w = value == 120;
x = value == 140;
y = value == 160;
z = value == 180;
Taking aside the semantics, this will also make it likely a bit more performant than a if/else structure. You might think that just running a single comparison will make it faster, so the first solution should be better, but in fact, branching can be slow. And since comparison operations are actually really fast, just assigning the result of a comparison four times is likely “faster”.
Note that none of this will actually have any real performance impact. Both is very low-level and it’s very likely that you have something else in your application’s code that is way slower, being a likelier bottle neck. So I wouldn’t stress about using one or another way for performance here; just choose what is semantically correct and then use whatever solution makes the semantics as clear as possible.
I know a switch would easily defeat the both in terms of performance.
A switch statement gives you the same effect as a chain of ifs and elses, so there isn’t really a difference here.
I guess another question inside this question would be what are the Big-O comparisons between the two?
Both is linear, as you just loop through the list. Every other difference is constant, so it doesn’t matter in Big-O notation.
The two function entirely differently. Performance is irrelevant; they don't do the same thing.
The first snippet sets the appropriate variable to true if the condition is met, and does nothing if the corresponding condition isn't met, meaning it leaves the original value.
The second snippet assigns a value to each variable on each iteration.
So the first snippet is effectively asking, "is any value equal to this number" for each of the numbers, the second snippet is effectively asking, "is the last value equal to this number" for each of the numbers. I assume you intend the former, not the latter, so the latter is simply wrong.
Well, in the case of integers, I really like to use a switch when I have too many cases. #ima explains it in this answer. Otherwise, it only matters what looks better or more "readable"
However using a switch with strings is a totally different story as explained in this post.

Using Catch Blocks to Return, Bad Idea?

This may be a stupid question, but I'm interested in the performance of using try/catch blocks.
I have a DataGrid that assigns a Converter to the background property of a DataGridCell. In the converter, I compare the value of this year's data to last year's data; if this year's data is > 3%, I return a Green background; if it's > 0% and < 3%, I return a Yellow; and if it's < 0%, I return Red:
string x = values[0].ToString().Replace("$", "").Replace(",", ""); //This year's number
string y = values[1].ToString().Replace("$", "").Replace(",", ""); //Last year's
result = (((float.Parse(x) * 100) / float.Parse(y)) - 1) * 100;
if (result >= 3)
return Brushes.LimeGreen;
else if (result >= 0)
return Brushes.Yellow;
else
return Brushes.Red;
However, in some cases, the cell will NOT have a value of last year; as you can guess, dividing by 0 (or some text as the Converter seems to receive when the Cell is empty) is a pretty bad idea and will throw an exception. So, I decided the easiest way to deal with this was:
try
{
result = (((float.Parse(x) * 100) / float.Parse(y)) - 1) * 100;
}
catch
{
return Brushes.DarkOrange;
}
So if the exception is thrown (whereby there is no value to compare to), return an Orange and call it a day. (edit: yes, I do wish to return an Orange when there is no value to compare to.
Currently, I can predict that it will only happen to one row of data for now, so it only catches about 10 cells when it's populated. But as the future goes on, it has the possibility of having it happen more times.
The try/catch block is the easiest and quickest way to handle this(as far as I can tell), but it is obviously not the only way, especially since I know the error. So Is using a try/catch block a bad idea in this case? And by bad idea, I mean will it slow performance since it is iterated over many, many times? Given that I know what the error will be, should I preempt it, or is using a try/catch block fine?
This is a bad idea. It's not an exceptional situation, so don't handle it like it's one. The fact that you're worried about performance and exception handling is a smell that you're doing something wrong. There is a really simple way to handle this, so I don't even see why you ever thought to instead handle it using exception handling.
Yes, it will impact your performance but that shouldn't be your concern here. Your concern should be what is the clearest way to write this logic, and using exceptions is clearly not the way.
Here's that simple way:
double value;
if(!Float.TryParse(y, out value) || value == 0f) {
return Brushes.DarkOrange;
}
else {
double result = (((float.Parse(x) * 100) / value) - 1) * 100;
if (result >= 3) {
return Brushes.LimeGreen;
}
else if (result >= 0) {
return Brushes.Yellow;
}
else {
return Brushes.Red;
}
}
In general, exceptions should be used for truly exceptional cases - cases which are not expected. In a situation like this, where you're well aware that there could be no prior year, I'd suggest using simple if() checks to return your default values.
To answer your performance question, Microsoft says that "Throwing exceptions can negatively impact performance".
The try catch has one of the worst performances on the .Net framework. Look here When an exception is raised the stacktrace has to be checked to find in which method there is a catch for that specific exception and this is a costly operation.
Never do things like that with exceptions if you have performance in mind (and I would say even if you don't have performance on mind).
Catch statements should only be used for catching Exceptions..Not altering the program flow, So to answer your question, yes this is a bad idea.
And I can't imagine it to be performant, because a new Exception object will be created and most likely java will do some logging of the event, so your better of just using an if statement.
Using the catch block in the way you described in your question is a bad idea. Try-catch blocks themselves do not have a huge performance impact, but exceptions do have a large performance cost.
The best option is to use the TryParse method on the float class instead. There is a reason it exists.
I believe Rico Mariani has the last word, as usual:
The True Cost of .NET Exceptions
Yes, using a Try/Catch block is a very bad idea.
I am not familiar enough with the intricacies of c# to tell you whether an if, or a tryparse statement or a try catch are going to be faster. What I can offer you is the idea of thinking about calls.
If you're worried about performance on something as simple as implementation of the same process, think about the number of calls as well. If you check every single number if it's 0, or call try-parse on every single number then you're adding that call to every iteration, not just the iterations that fail. If this implementation works for you, it is a good approach as it only gets into the catch block when it fails.
For many programs, this sort of implementation wouldn't work, because they want to do additional processing in the catch block. For those programs, you'd want to check for the 0, or do the tryparse. Since you're just returning, I believe this makes for easily readable code.

if(value == null) vs if(null == value) [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Why does one often see “null != variable” instead of “variable != null” in C#?
This is more a curiosity question, is there any performance difference between the statement.
if(value == null)
and
if(null == value)
is it noticeable, I use c#, PHP & javascript quite often and I remember someone saying if(null == value) was faster, but is it really?
I will soon be starting development on an application that will parse huge quantities of data in the region of Terabytes so even if the performance gain is in the millisecond range it could have an impact. Anyone have any ideas?
I doubt that there's a measurable performance advantage either way. I'll bet the person who told you this didn't have any hard data.
As far as I know, it's a historical artifact, a technique from C and C++ to guard against this mistake:
if (c = null) {
}
The compiler will catch this if you reverse the arguments, since you can't assign something to null.
I profiled both over 100 million iterations.
if(value == null)
-- 6.85175704956 seconds (68.5 nano-seconds each)
if(null == value)
-- 6.75543808937 seconds (67.5 nano-seconds each)
So it's up to you if 1 nanosecond is enough of a gain.
There is absolutely no performance difference to be expected.
The only reason the (ugly) form (if null == value) is used is to avoid a C/C++ specific typo:
if (value = null) // compiles but _assigns_ null to value and always returns false
... // never executed
I think it's fair to expect there will be no difference: it's such a simple case that if there was a difference the compiler would make sure to generate the fastest version anyway.
Yes I also think there will be no difference, but personally I prefer if(value == null)
Optimizations like this will gain you a clock cycle at best (I wouldn't know why though). But most likely if it is any better, then the compiler will optimize it for you.
The reason to put any literal (such as null) first is that you can not accidentally assign the value if you do = instead of ==. I personally do find it less readable though.
I'm not sure if it's faster or not but some languages allow you to assign in an if statement without warning you so if you do:
if (value = null) by mistake you could wipe your variable, whereas the other way around wouldn't cause weird issues further on down the execution path.

Different ways of writing the "if" statement [closed]

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 8 years ago.
Improve this question
I have seen different ways of writing an if statement.
Which one do you prefer and why?
Example 1:
if (val % 2 == 1){output = “Number is odd”;}else{output = “Number is even”;}
Example 2:
if (val % 2 == 1)
{
output = “Number is odd”;
}
else
{
output = “Number is even”;
}
Example 3:
if (val % 2 == 1)
output = “Number is odd”;
else
output = “Number is even”;
Example 4:
if (val % 2 == 1){
output = “Number is odd”;
} else {
output = “Number is even”;
}
Similar question:
Why is it considered a bad practice to omit curly braces?
For cases like this, there's also the conditional operator:
output = (val % 2 == 1) ? "Number is odd" : "Number is even";
If you're definitely going to use an "if" I'd use version 2 or version 4, depending on the rest of your bracing style. (At work I use 4; for personal projects I use 2.) The main thing is that there are braces even around single statements.
BTW, for testing parity it's slightly quicker to use:
if ((val & 1) == 1)
Version 2. I always include the brackets because if you ever need to put more than one line under the conditional you won't have to worry about putting the brackets in at a later date. That, and it makes sure that ALL of your if statements have the same structure which helps when you're scanning code for a certain if statement.
I use version 2.
One reason to use curly braces becomes more clear if you don't have an else.
if(SomeCondition)
{
DoSomething();
}
If you then need to add another line of code, you are less likely to have an issue:
if(SomeCondition)
{
DoSomething();
DoSomethingElse();
}
Without the braces you might have done this:
if(SomeCondition)
DoSomething();
DoSomethingElse();
I personally prefer 3. The extra curly braces just add too much unnecessary visual noise and whitespace.
I can somewhat see the reasoning for 2/4 to reduce bugs, but I have personally never had a bug because thinking extra lines were inside an if statement. I do use C# and visual studio so my code always stays pretty well formatted. This could however be a problem if I was a more notepad style programmer.
I prefer #2. Easy readability.
None of the above.
If my execution block only has one line (even if it's a huge for statement) then I don't use braces, but I do indent it, similar to #3
if (num > 3)
print "num is greater than 3";
else
print "num is not greater than 3";
An example with multiple statements that do not need curly braces:
if (num > 3)
for (int i = 0; i < 100)
print i + "\n";
else
print "booya!";
That said, Jon Skeet's response in this question is the best
It is more important to be consistent than to select the best.
These styles have different advantages and drawbacks, but none is as bad as mixing them within a project or even a compilation unit or within a function.
Ternary operator is the obvious choice for this specific code. For simple single statement if/else's that can't be otherwise expressed, I'd prefer a properly indented case 3:
if (val % 2 == 1)
output = “Number is odd”;
else
output = “Number is even”;
I understand the motivation behind "always use braces", but I've personally never been bitten by their omission (OK, once. With a macro.)
From the above styles, I'd pick (2). (4) would be ok if "properly" indented.
(1) I'd attribute to a young developer who hopefully will grow out of "compact code", or someone who can't afford a decent monitor. Still, I'd go with it if it was the local style.
I use version 2.
I agree with the ternary operator. Very under utilized in code that I come across, and I think it is much easier and nicer to read than all the extra brackets and indents it takes to write out an if/else statement.
It's strange that nobody mentioned this:
if ( x == 1) {
...
}
else {
...
}
To me, this is the only correct way, of course :-)
I prefer 4 myself, but I think 2 is definitely good too.
Personally, there are two methods that I find being good-practice:
For if-blocks, there's only this way:
if(...)
{
// ...
}
else if (...)
{
// ...
}
else
{
// ...
}
This is the safest and most comprehensible way to write if-else-blocks.
For one liners (true one liners that are comprehensible on one line), you can use the ternary operator.
var objectInstance = condition ? foo : bar;
// Or the binary operator when dealing with null values
var objectInstance = condition ?? foo;
You shouldn't call methods that do something that do not help the current assignation.
I wouldn't use any other way than those stated above.
Version #2 for me - easiest to see, easiest to read, easy to see where the if starts and ends, same for else, you dont have to worry about putting in brackets if you want to add more than one statement.
I would use them in the following order:
1) the Ternary operator
2) example 3, but indented properly
3) either 2 or 4, they are basically the same. I would go with whatever the general styl was where I worked.
I agree with what jake said about omitting the unnecessary curly braces. I have never caused or seen a bug caused by new code being added and someone thinking they were part of an if statement but they weren't because of the lack of curly braces. If someone ever did do that, I would ridicule them mercilessly.
You'd have to torture me to get me to use number 1.
I'd always use #2. #4 is a truly awful layout and would only be done by someone who believes that a method must be one screen size in length and will do anything to cram it in, rather than refactor the code!!!
Personally I prefer version 2. But since it's only formating it doesn't matter. Use which is best readable for you and your team members!
I use a #2 with a minor change
if (condition1)
{
doStuff();
} else
{
doSomethingElse();
}
Single short statements:
if (condition) output = firstChoice;
else doSomethingElse();
Multiple or long statements
if (condition) {
output = firstChoice;
...
} else {
...
}
using with the braces is suggested, I have seen some issue with the if else statement without braces ,(I don't remember exactly) i.e. Statement under if was not executed, when I added the same with braces then only worked.( Using Visual studio & C#4.0).
Example 2 is without a doubt the least error prone approach. Please see this answer I gave to a similar question for the reason why:
What is the prefered style for single decision and action statements?
Although the Visual Studio default for brace usage is to put braces on a newline (my preferred method), the Framework Design Guidelines book (first edition) by Krzysztof Cwalina and Brad Abrams propose a different convention, example 4, placing the opening brace at the end of a preceding if statement (Page 274). They also state "Avoid omitting braces, even if the language allows it".
Not having the second edition at hand, I couldn't say if these conventions have changed or not.

Categories

Resources