|
May I please inquire the manner in which code safety is promoted via the presented K&R format. I assume it refers to the risk of programmer error making the assumption braces reduce the risk of further editing incorrectly. That seems reasonable. Than there are the matters of personal preference re/ visual processing also screen real estate. Perhaps in future the IDE will provide a feature I have contemplated id est coloring each block in a differing color.
btw the matching braces which are not vertically aligned in your presented specimen prevent the IDE from displaying vertical dots betwixt them. A feature I quite prefer.
-kind regards
|
|
|
|
|
The K&R format is unrelated to code safety. You get that by using braces.
Using (or not using) the K&R style is purely a matter of personal taste and convention. Code in Java and Javascript are almost always written in K&R form, but that's purely by convention.
/ravi
|
|
|
|
|
I would rather use 'Assert' in the 'else {}' part to document the code and catch any possible problem, for example after a bad code editing.
|
|
|
|
|
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]
|
|
|
|
|
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
{
}
|
|
|
|
|
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.
|
|
|
|
|
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 (<Boolean test>) {
...
}
else
{
...
}
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
|
|
|
|
|
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.
|
|
|
|
|
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)
{
}
else if (condition 2)
{
}
else
{
}
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)
else if (condition 2)
else
The 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)
else if (condition 2)
else
In 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:
break;
case 2:
break;
case 3:
break;
default:
break;
}
Once your application starts to grow in complexity, then you start to contend with nesting:
if (condition 1)
{
if (condition 2)
{
}
else if (condition 3)
{
if (condition 4)
{
}
}
}
This quickly becomes a nightmare to test and maintain. Testing requires the exercising of all logical branches, which this format complicates.
It quickly becomes evident that a better abstraction and/or implementation would be better suited. In the case of states, where a change of state triggers an execution of code and a transition to a new state, then a state machine would be better suited here to replace the if/else scaffolding (beyond the scope of this response).
And so it goes...
BTW, there are valid cases where the second format form of if/else would be better suited. For the case of nullable types i.e. bool? var, sometimes explicitly spelling out the true and false cases makes for better reading and comprehension:
bool? state;
...
if (state == true)
{
}
else if (state == false)
{
}
else
{
}
There's more than one way to skin and if/else clause!
|
|
|
|
|
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.
|
|
|
|
|
Stacy Dudovitz wrote: often unit testing is more to tick off a checkbox
That can be solved with required code reviews and required code coverage metrics.
|
|
|
|
|
Agree on the curly braces. There was someone who did a lot of research about which if/else brace pattern worked best for automated merging, but I can never find it.
|
|
|
|
|
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 {
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.
π
|
|
|
|
|
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
|
|
|
|
|
Wordle 951 3/6
β¬β¬π©β¬β¬
π©π©π©π¨β¬
π©π©π©π©π©
|
|
|
|
|
Wordle 951 3/6*
π©β¬π©β¬β¬
π©π©π©β¬β¬
π©π©π©π©π©
"I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
"Common sense is so rare these days, it should be classified as a super power" - Random T-shirt
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
Wordle 951 6/6
β¬β¬β¬β¬β¬
β¬β¬β¬β¬π¨
β¬π©π©β¬β¬
β¬π©π©β¬β¬
π¨π©π©π©β¬
π©π©π©π©π©
Phew
|
|
|
|
|
β¬β¬π¨β¬β¬
β¬β¬π©β¬β¬
π¨π©π©π¨β¬
π©π©π©π©π©
In a closed society where everybody's guilty, the only crime is getting caught. In a world of thieves, the only final sin is stupidity. - Hunter S Thompson - RIP
|
|
|
|
|
Wordle 951 5/6
β¬π©π¨β¬β¬
π©π©β¬β¬β¬
π©π©β¬β¬β¬
π©π©β¬π©β¬
π©π©π©π©π©
|
|
|
|
|
Wordle 951 4/6*
β¬β¬π¨π¨β¬
π¨π¨β¬β¬β¬
π©π©β¬π©β¬
π©π©π©π©π©
Happiness will never come to those who fail to appreciate what they already have. -Anon
And those who were seen dancing were thought to be insane by those who could not hear the music. -Frederick Nietzsche
|
|
|
|
|
Wordle 951 6/6*
π©β¬π©β¬β¬
π©β¬π©β¬β¬
π©β¬π©β¬β¬
π©β¬π©β¬β¬
π©β¬π©β¬π¨
π©π©π©π©π©
I didn't find that easy!
|
|
|
|