if else Style
-
Greetings & Kind Regards I seek advice and knowledge of others' practice re/ a minor matter of style. In particular to be specific I vacillate betwixt and between two forms of final statement of if ... else ... series of statements assuming every possible condition is accounted for as shown in simple specimen / example / sample below (not snippet as it is not a snip of a larger code base). 1st style : if(expression == true) {...} else {...} 2nd style : if(expression == true) {...} else if(expression == false) {...} Note it is the final statement I am inquiring regards. Do your kind selves accept the default final result as shown in 1st style or perform explicit unnecessary test as shown in 2nd style for no other reason than to make the code self documenting and easier to understand in particular for a complex lengthy series of conditions. btw in 2nd style on occasion I add as final statement else throw who_the_heck_knows_what_happened; Thank You Kindly [edit] I have concluded kind Jacquers is quite correct. As it happened upon some coding just now of a simple series of such it was evident an explicit final test results in confusion as it is clearly not necessary. However in a lengthy complex series an explicit test makes code self documenting and so simpler to understand. KISS
This is a good question! It happens in real life and doesn't get discussed much though! I recommend that you do *not* put in the extra test, because... > If there is any future maintenance involving a change to the condition the future programmer will need to review both conditions. Extra comprehension, extra code - more likely an error or misunderstanding. > a comment would serve the same purpose - and even can be removed safely > ? If you have both tests, then ask what's the "else" for? My experience - I've seen this done in the past, and it just trips up future programmer and confuses the human reader. [my edit: - Absolutely agree with Iacopo Vettori's comment - use 'Assert' for such cases]
-
Greetings & Kind Regards I seek advice and knowledge of others' practice re/ a minor matter of style. In particular to be specific I vacillate betwixt and between two forms of final statement of if ... else ... series of statements assuming every possible condition is accounted for as shown in simple specimen / example / sample below (not snippet as it is not a snip of a larger code base). 1st style : if(expression == true) {...} else {...} 2nd style : if(expression == true) {...} else if(expression == false) {...} Note it is the final statement I am inquiring regards. Do your kind selves accept the default final result as shown in 1st style or perform explicit unnecessary test as shown in 2nd style for no other reason than to make the code self documenting and easier to understand in particular for a complex lengthy series of conditions. btw in 2nd style on occasion I add as final statement else throw who_the_heck_knows_what_happened; Thank You Kindly [edit] I have concluded kind Jacquers is quite correct. As it happened upon some coding just now of a simple series of such it was evident an explicit final test results in confusion as it is clearly not necessary. However in a lengthy complex series an explicit test makes code self documenting and so simpler to understand. KISS
Every place I've worked that used C/C++ in the past 35 years dictated this style (and it's my style of choice). if () { } else if { } else { }
-
Greetings & Kind Regards I seek advice and knowledge of others' practice re/ a minor matter of style. In particular to be specific I vacillate betwixt and between two forms of final statement of if ... else ... series of statements assuming every possible condition is accounted for as shown in simple specimen / example / sample below (not snippet as it is not a snip of a larger code base). 1st style : if(expression == true) {...} else {...} 2nd style : if(expression == true) {...} else if(expression == false) {...} Note it is the final statement I am inquiring regards. Do your kind selves accept the default final result as shown in 1st style or perform explicit unnecessary test as shown in 2nd style for no other reason than to make the code self documenting and easier to understand in particular for a complex lengthy series of conditions. btw in 2nd style on occasion I add as final statement else throw who_the_heck_knows_what_happened; Thank You Kindly [edit] I have concluded kind Jacquers is quite correct. As it happened upon some coding just now of a simple series of such it was evident an explicit final test results in confusion as it is clearly not necessary. However in a lengthy complex series an explicit test makes code self documenting and so simpler to understand. KISS
As you wrote it, the 1st style is correct. Meaning an expression evaluates to true or false. The else if injects a potential question when re-reading the code that another possibility exists. If it were if(boolvar==true)..., there may be cases where the else if is appropriate.
-
Greetings & Kind Regards I seek advice and knowledge of others' practice re/ a minor matter of style. In particular to be specific I vacillate betwixt and between two forms of final statement of if ... else ... series of statements assuming every possible condition is accounted for as shown in simple specimen / example / sample below (not snippet as it is not a snip of a larger code base). 1st style : if(expression == true) {...} else {...} 2nd style : if(expression == true) {...} else if(expression == false) {...} Note it is the final statement I am inquiring regards. Do your kind selves accept the default final result as shown in 1st style or perform explicit unnecessary test as shown in 2nd style for no other reason than to make the code self documenting and easier to understand in particular for a complex lengthy series of conditions. btw in 2nd style on occasion I add as final statement else throw who_the_heck_knows_what_happened; Thank You Kindly [edit] I have concluded kind Jacquers is quite correct. As it happened upon some coding just now of a simple series of such it was evident an explicit final test results in confusion as it is clearly not necessary. However in a lengthy complex series an explicit test makes code self documenting and so simpler to understand. KISS
For short, simple IF/ELSE statements, I do not use the ELSE IF (false) because it is unnecessary. If there are a large number of statements inside the IF block, then I'll use
IF () {
...
}
else //Not {
...
}This allows me to document the code with a simple comment since the IF test is too far away from the ELSE.
Bond Keep all things as simple as possible, but no simpler. -said someone, somewhere
-
I do hope that the "==true" and "==false" are not meant literally! A programmer comparing a logical expression against "true" or "false" have not understood what is meant by a logical expression. I wonder how many of those programming that way also speak that way! "If you have a moment to spare is true, I want a talk with you", or "If the door is unlocked is false, you'll find the key under the door mat" - noone that I know speaks that way. I have met a few programmers who program that way, but I never heard any of them speak with "is true" or "is false".
Religious freedom is the freedom to say that two plus two make five.
I have frequently seen programmers from India use
if (variable == true){...}
in their code. I really don't understand it. But to be fair, their variables names do not make it clear that it's a Boolean value. All of my Boolean variables' names are a Yes/No question (IsValid, DoneProcessing, DoUseQuotes, etc.) so it's obviously a Boolean. When your Boolean variables are named poorly (Validation, Finish, Quotes, etc.), then you need the "== Boolean" in order to know what is going on.
Bond Keep all things as simple as possible, but no simpler. -said someone, somewhere
-
As others have said, it depends on the context. I prefer a ternary operator if I must choose between returning one of two results:
Foo foo = (condition ? Foo1 : Foo2);
For choosing different actions, I prefer the if/then/else style, even if it would be possible to write this as a ternary expression:
if (condition)
{
expressions1;
}
else
{
expressions2;
}A "cascading" if/then/else is useful for subordinate cases:
if (condition1)
{
expressions1;
}
else
{
if (condition2)
{
expressions2;
}
else
{
expressions3;
}
}Note that there is angoing debate whether good style requires that one wrap even single expressions in curly brackets. ( {...} }. If is usually not required by the language, but can help clarify the flow. Note that there are cases where a "cascading ternary operator" can also be useful, and actually clearer than the "cascading if/then/else".
Freedom is the freedom to say that two plus two make four. If that is granted, all else follows. -- 6079 Smith W.
In languages were the braces (other other syntax) is not required to block out an IF or ELSE block of code, I have seen many bugs where someone got it wrong, or edited it much later incorrectly. In my code reviews, I enforce having them for all cases because it's impossible to get wrong were the code block starts and stops; there is no interpretation of non-visible cues needed.
Bond Keep all things as simple as possible, but no simpler. -said someone, somewhere
-
Greetings & Kind Regards I seek advice and knowledge of others' practice re/ a minor matter of style. In particular to be specific I vacillate betwixt and between two forms of final statement of if ... else ... series of statements assuming every possible condition is accounted for as shown in simple specimen / example / sample below (not snippet as it is not a snip of a larger code base). 1st style : if(expression == true) {...} else {...} 2nd style : if(expression == true) {...} else if(expression == false) {...} Note it is the final statement I am inquiring regards. Do your kind selves accept the default final result as shown in 1st style or perform explicit unnecessary test as shown in 2nd style for no other reason than to make the code self documenting and easier to understand in particular for a complex lengthy series of conditions. btw in 2nd style on occasion I add as final statement else throw who_the_heck_knows_what_happened; Thank You Kindly [edit] I have concluded kind Jacquers is quite correct. As it happened upon some coding just now of a simple series of such it was evident an explicit final test results in confusion as it is clearly not necessary. However in a lengthy complex series an explicit test makes code self documenting and so simpler to understand. KISS
BernardIE5317 wrote:
if(expression == true) {...}
I had forgotten another variance on mandating usage.
if(true == expression)
Some C++ coders insisted on that because, the possibility existed that one might code the following.
if(expression = true)
And that is valid in C++. Myself C++ programmers not controlling the scope of the their memory allocations was always, and still is, much more of a significant problem.
-
yeah, the brace on the same line makes me want to puke.
Charlie Gilley “They who can give up essential liberty to obtain a little temporary safety deserve neither liberty nor safety.” BF, 1759 Has never been more appropriate.
Wholeheartedly agree! Having the braces on separate lines makes it so much easier to determine where the then/else clauses begin and end. Lining them up vertically at each indentation level also means you can easily see what goes with what, such as: if (expression) { // then result if (other condition) { // Other condition then result } else { // other condition else result } } else { // else result } I really hate code that puts all the opening braces on the if (expression) line, or the "else" line. Programmers who don't believe in clarity of their code should be banned from the practice. Don't forget -- comments can also help a lot in improving clarity.
-
Wholeheartedly agree! Having the braces on separate lines makes it so much easier to determine where the then/else clauses begin and end. Lining them up vertically at each indentation level also means you can easily see what goes with what, such as: if (expression) { // then result if (other condition) { // Other condition then result } else { // other condition else result } } else { // else result } I really hate code that puts all the opening braces on the if (expression) line, or the "else" line. Programmers who don't believe in clarity of their code should be banned from the practice. Don't forget -- comments can also help a lot in improving clarity.
Norm Powroz wrote:
Having the braces on separate lines makes it so much easier to determine where the then/else clauses begin and end.
You have indentation for that, don't you? If you indent neither of the braces, they do not enforce the indentation, but blurs both the indentation and the keyword causing the indentation. If you indent both, the keyword is 'revealed'. And the block is extended by two two lines, making it more prominent. I think that making 'the indenting keyword' more visible (by avoiding the blurring opening brace immediately below it) is a good thing. Indenting before the opening brace is logically inconsistent - so the brace should be un-indented, at the line of the if / while / ... . Also, when you read e.g. an if, and the line ends abruptly, with no explanation, you should rather include the brace to indicate: There is an explanation - this brace tells that a block is following! The closing brace on a separate indented line ensures that the indented block is at least two lines long. That should be enough for everybody, to make sure that the block is easily identified. I think un-indented braces blur the indented block, rather than enforcing it as it should.
Religious freedom is the freedom to say that two plus two make five.
-
Greetings & Kind Regards I seek advice and knowledge of others' practice re/ a minor matter of style. In particular to be specific I vacillate betwixt and between two forms of final statement of if ... else ... series of statements assuming every possible condition is accounted for as shown in simple specimen / example / sample below (not snippet as it is not a snip of a larger code base). 1st style : if(expression == true) {...} else {...} 2nd style : if(expression == true) {...} else if(expression == false) {...} Note it is the final statement I am inquiring regards. Do your kind selves accept the default final result as shown in 1st style or perform explicit unnecessary test as shown in 2nd style for no other reason than to make the code self documenting and easier to understand in particular for a complex lengthy series of conditions. btw in 2nd style on occasion I add as final statement else throw who_the_heck_knows_what_happened; Thank You Kindly [edit] I have concluded kind Jacquers is quite correct. As it happened upon some coding just now of a simple series of such it was evident an explicit final test results in confusion as it is clearly not necessary. However in a lengthy complex series an explicit test makes code self documenting and so simpler to understand. KISS
In reading all of the responses, I'm quite surprised that the only alternative mentioned was the tertiary operator (?: ). While it's simple to respond 'context dependent' as I saw in some of the replies, I think maybe it would help to spell out the concerns as well as offer up more choices. Let's start with the elephant in the room... readability and maintainability. They both go hand in hand to answer the question "what are you trying to do or say in the code?" In addition, some of the choices can lead to both bugs and code creep. Let's start with if/else as a potential solution to express a/the logical path to traverse. A couple of simple rules would help (these are *my* rules, some may be obvious, but some are what I call 'Where's the curly brace' religious preferences. Take everything I write here are my own style rather than engage in religiosity).
if (condition 1)
{
// do something 1
}
else if (condition 2)
{
// do something 2
}
else
{
// do something 3
}I always include the curly braces to ensure that scope is honored i.e. what code is executed based on which condition is met. Too often I've see this:
if (condition 1)
// do something 1
else if (condition 2)
// do something 2
else
// do something 3The problem here is if another author comes in to add/maintain the code, and adds a second line of execution to one of the conditions. If that author forgets to now add the curly braces to enclose scope, bad things happen.
if (condition 1)
// do something 1
else if (condition 2)
// do something 2A
// do something 2B <-- we've exited the scope of the if/else clause. Ooops!
else
// do something 3In addition, the whole Nickleback induced hatred the tertiary operator hails back to a late 70's bug introduced in a version (or couple of versions) of the Whitesmiths C compiler, and has since become lore. If we are striving for readability, then:
if (condition) ? "do one thing" : "do the other thing";
If you are vehemently opposed to this, chances are you also avoid the null coalescing as well as other similar constructs:
char *s = null;
char *t = null;
...t = s ? "some string" : "some default";
But really, is this the only way to proceed? How about:
switch (operand)
{
case 1:
// do something case 1
break;
case 2:
// do something case 2
break;
case 3:
// do something case 3 -
In reading all of the responses, I'm quite surprised that the only alternative mentioned was the tertiary operator (?: ). While it's simple to respond 'context dependent' as I saw in some of the replies, I think maybe it would help to spell out the concerns as well as offer up more choices. Let's start with the elephant in the room... readability and maintainability. They both go hand in hand to answer the question "what are you trying to do or say in the code?" In addition, some of the choices can lead to both bugs and code creep. Let's start with if/else as a potential solution to express a/the logical path to traverse. A couple of simple rules would help (these are *my* rules, some may be obvious, but some are what I call 'Where's the curly brace' religious preferences. Take everything I write here are my own style rather than engage in religiosity).
if (condition 1)
{
// do something 1
}
else if (condition 2)
{
// do something 2
}
else
{
// do something 3
}I always include the curly braces to ensure that scope is honored i.e. what code is executed based on which condition is met. Too often I've see this:
if (condition 1)
// do something 1
else if (condition 2)
// do something 2
else
// do something 3The problem here is if another author comes in to add/maintain the code, and adds a second line of execution to one of the conditions. If that author forgets to now add the curly braces to enclose scope, bad things happen.
if (condition 1)
// do something 1
else if (condition 2)
// do something 2A
// do something 2B <-- we've exited the scope of the if/else clause. Ooops!
else
// do something 3In addition, the whole Nickleback induced hatred the tertiary operator hails back to a late 70's bug introduced in a version (or couple of versions) of the Whitesmiths C compiler, and has since become lore. If we are striving for readability, then:
if (condition) ? "do one thing" : "do the other thing";
If you are vehemently opposed to this, chances are you also avoid the null coalescing as well as other similar constructs:
char *s = null;
char *t = null;
...t = s ? "some string" : "some default";
But really, is this the only way to proceed? How about:
switch (operand)
{
case 1:
// do something case 1
break;
case 2:
// do something case 2
break;
case 3:
// do something case 3 -
Stacy Dudovitz wrote:
If that author forgets to now add the curly braces to enclose scope, bad things happen.
So not only coding now to guess at the competence of future programmers but also presuming that comprehensive unit testing will not happen?
To the first question about competence, that may be a bit harsh. We are, after all, human beings, and as such, even the best of us make mistakes. To be clear, while some mistakes can be attributed to competency levels and/or experience, I've also seen errors due to time pressure from the decisions makers, long hours of debugging a nasty problem, or other factors which can contribute to bugs. Hence, my suggestion/recommendation falls more in line with defensive coding rather than assuming that everyone that is not me is an idiot. Your mileage may vary on that point. With regards to unit testing, even in shops where unit testing is mandated as part of the development process (again, until a time deadline or other external factors discourage the practice in light of external pressures), my experience has been that often unit testing is more to tick off a checkbox than to actually produce maintainable and reliable code. Writing proper unit test code is an artform unto itself, and is predicated on other practices such as one method should encompass exactly one function. (Lets not split hairs on the triumvirate of the types of testing i.e. unit, system and integration tests. In this case I am referring to all three under the single banner of 'unit testing'.) Bottom line, whatever practice you or your shop choose to implement, it should be purposeful and consistent. My post here was to offer a more thorough response to the original question.
-
Greetings & Kind Regards I seek advice and knowledge of others' practice re/ a minor matter of style. In particular to be specific I vacillate betwixt and between two forms of final statement of if ... else ... series of statements assuming every possible condition is accounted for as shown in simple specimen / example / sample below (not snippet as it is not a snip of a larger code base). 1st style : if(expression == true) {...} else {...} 2nd style : if(expression == true) {...} else if(expression == false) {...} Note it is the final statement I am inquiring regards. Do your kind selves accept the default final result as shown in 1st style or perform explicit unnecessary test as shown in 2nd style for no other reason than to make the code self documenting and easier to understand in particular for a complex lengthy series of conditions. btw in 2nd style on occasion I add as final statement else throw who_the_heck_knows_what_happened; Thank You Kindly [edit] I have concluded kind Jacquers is quite correct. As it happened upon some coding just now of a simple series of such it was evident an explicit final test results in confusion as it is clearly not necessary. However in a lengthy complex series an explicit test makes code self documenting and so simpler to understand. KISS
-
Do not attempt the extra check if you are dealing with floating points. You might really need the extra ELSE clause. if (x > 1.0) { } else if (x <= 1.0) { } else { // yes you can reach this throw wtf; } What are possible values of x?
Disagree! (contingent on compiler switches set, of course :) )
else {
// yes you can reach this
throw wtf;
}if (x == NaN) or some similar hairy answer, the compiler (again, with the correct compilation switches set) will automagically throw an exception. Sidebar: One would NOT want to set said same switches on an embedded piece of code, since typically exception handling is turned off. Therefore, one would NOT, in such an instance wish to
throw wtf
. -
BernardIE5317 wrote:
if(expression == true) {...}
I had forgotten another variance on mandating usage.
if(true == expression)
Some C++ coders insisted on that because, the possibility existed that one might code the following.
if(expression = true)
And that is valid in C++. Myself C++ programmers not controlling the scope of the their memory allocations was always, and still is, much more of a significant problem.
jschell wrote:
if(true == expression)
sometimes referred to as Yoda formatting.
-
To the first question about competence, that may be a bit harsh. We are, after all, human beings, and as such, even the best of us make mistakes. To be clear, while some mistakes can be attributed to competency levels and/or experience, I've also seen errors due to time pressure from the decisions makers, long hours of debugging a nasty problem, or other factors which can contribute to bugs. Hence, my suggestion/recommendation falls more in line with defensive coding rather than assuming that everyone that is not me is an idiot. Your mileage may vary on that point. With regards to unit testing, even in shops where unit testing is mandated as part of the development process (again, until a time deadline or other external factors discourage the practice in light of external pressures), my experience has been that often unit testing is more to tick off a checkbox than to actually produce maintainable and reliable code. Writing proper unit test code is an artform unto itself, and is predicated on other practices such as one method should encompass exactly one function. (Lets not split hairs on the triumvirate of the types of testing i.e. unit, system and integration tests. In this case I am referring to all three under the single banner of 'unit testing'.) Bottom line, whatever practice you or your shop choose to implement, it should be purposeful and consistent. My post here was to offer a more thorough response to the original question.
-
Disagree! (contingent on compiler switches set, of course :) )
else {
// yes you can reach this
throw wtf;
}if (x == NaN) or some similar hairy answer, the compiler (again, with the correct compilation switches set) will automagically throw an exception. Sidebar: One would NOT want to set said same switches on an embedded piece of code, since typically exception handling is turned off. Therefore, one would NOT, in such an instance wish to
throw wtf
.The OP never mentioned language or compilers. Some compilers for whatever language may not support those options. It was a general stylistic question. Most compilers (and forums) won’t even warn when you use assignment operator instead of comparison operator. 😊
-
In reading all of the responses, I'm quite surprised that the only alternative mentioned was the tertiary operator (?: ). While it's simple to respond 'context dependent' as I saw in some of the replies, I think maybe it would help to spell out the concerns as well as offer up more choices. Let's start with the elephant in the room... readability and maintainability. They both go hand in hand to answer the question "what are you trying to do or say in the code?" In addition, some of the choices can lead to both bugs and code creep. Let's start with if/else as a potential solution to express a/the logical path to traverse. A couple of simple rules would help (these are *my* rules, some may be obvious, but some are what I call 'Where's the curly brace' religious preferences. Take everything I write here are my own style rather than engage in religiosity).
if (condition 1)
{
// do something 1
}
else if (condition 2)
{
// do something 2
}
else
{
// do something 3
}I always include the curly braces to ensure that scope is honored i.e. what code is executed based on which condition is met. Too often I've see this:
if (condition 1)
// do something 1
else if (condition 2)
// do something 2
else
// do something 3The problem here is if another author comes in to add/maintain the code, and adds a second line of execution to one of the conditions. If that author forgets to now add the curly braces to enclose scope, bad things happen.
if (condition 1)
// do something 1
else if (condition 2)
// do something 2A
// do something 2B <-- we've exited the scope of the if/else clause. Ooops!
else
// do something 3In addition, the whole Nickleback induced hatred the tertiary operator hails back to a late 70's bug introduced in a version (or couple of versions) of the Whitesmiths C compiler, and has since become lore. If we are striving for readability, then:
if (condition) ? "do one thing" : "do the other thing";
If you are vehemently opposed to this, chances are you also avoid the null coalescing as well as other similar constructs:
char *s = null;
char *t = null;
...t = s ? "some string" : "some default";
But really, is this the only way to proceed? How about:
switch (operand)
{
case 1:
// do something case 1
break;
case 2:
// do something case 2
break;
case 3:
// do something case 3 -
Greetings & Kind Regards I seek advice and knowledge of others' practice re/ a minor matter of style. In particular to be specific I vacillate betwixt and between two forms of final statement of if ... else ... series of statements assuming every possible condition is accounted for as shown in simple specimen / example / sample below (not snippet as it is not a snip of a larger code base). 1st style : if(expression == true) {...} else {...} 2nd style : if(expression == true) {...} else if(expression == false) {...} Note it is the final statement I am inquiring regards. Do your kind selves accept the default final result as shown in 1st style or perform explicit unnecessary test as shown in 2nd style for no other reason than to make the code self documenting and easier to understand in particular for a complex lengthy series of conditions. btw in 2nd style on occasion I add as final statement else throw who_the_heck_knows_what_happened; Thank You Kindly [edit] I have concluded kind Jacquers is quite correct. As it happened upon some coding just now of a simple series of such it was evident an explicit final test results in confusion as it is clearly not necessary. However in a lengthy complex series an explicit test makes code self documenting and so simpler to understand. KISS
Hell no! If you must put the second conditional for documentation purposes, make it a comment if (cond) ... else // if (!cond) ... or if (cond) ... else // cond ... I've seen that style used for conditional compilation, not so much for braces. #if cond ... #else ... #endif //cond