I think both ways have their up- /downsides. The solution of u/dyingpie1 is more confusing than the original code, but the original code can cause exactly what happened to OPs teammate, overseeing the condition1 && !condition2 case.
Not necessarily. If there are any pointers in the middle or the conditions risk side effects the compiler won't generate it unless you specifically tell it to ignore them, even at high optimization levels.
You're right, there are in fact scenarios where details matter. But in general it almost never pays off to sacrifice readability just to save a few lines of code.
One of the most important wisdoms of SW engineering is: any fool can write a piece of code which can be interpreted by the machine. The true art lies in writing code which humans can understand.
Oh that I completely agree with. But I think people don't understand what compilers can and can't do. Generally simpler code is easier for a compiler to optimize, those stupid "creative solutions" tend to not only be harder to read but harder for a compiler to understand and optimize. Most times less is more.
Agree. Although modern compilers (I'm looking at you, gcc 10) can really do wonders.
My team is designing real-time software where literally ever microsecond, heck, nanosecond counts and because of that we actually have to inspect generated assembler code from time to time. Every time I do so, it amazes me what the gcc can detect and optimize.
Fully agree. Readability is always subjective. Some of us prefer few and compact lines others more elaborate sequences.
Either way there is one thing which is really annoying: Technology prima donnas who use obfuscated code to demonstrate that they are the best leet haxx0rs in the hood.
terrible mindset which seems to have been behind every single legacy project there is. clarity is important. the original was not only fine but pretty amazing.
terrible mindset which seems to have been behind every single legacy project there is.
I thought I made it sufficiently clear that I meant "it doesn't matter in terms of execution efficiency" Readability and clarity is, in fact, of essential importance.
To me, it’s actually less readable. I have to scan multiple areas to see what the code is doing. I would never refactor it to something i think is more readable, but maybe add a line or two of comments above the block describing what is happening, because my belief of readable is not the same as yours, is not the same as the other team members.
It looks like this comment contains a code block delimited with triple backticks. Unfortunately reddit does not have universal support for this syntax and your comment will not render correctly on old reddit and most mobile apps.
For the benefit of people on old reddit, this link will take you to a correct rendering of the comment.
/u/Rigatavr, it would be appreciated, but not required, if you could edit your comment to use the more compatible four space indention format. For single lines or inline code you can use single backticks.
If there's actually nothing else to be done in the function, sure. But this seems to be a stripped down example for the sake of safe sharing to Reddit, and I would guess that there's additional common behavior happening before the return. In that case, the if-elseif construction (assuming it's available in the language) will be superior.
Depending on codebase and what those conditions actually are this can end up more confusing for the reader than original. Compiler should handle it correctly but code is supposed to be human readable and preferrably to others than the original writer as well.
Consider complex conditions that depend on multiple variables breaking it down to something that's easy to follow becomes more important. Even more so if you deal with some kind of formal proof (safety critical code) or need complex unit tests to reach the special case: simple is just better. So depending on situation it might even be best to have the first case since compiler can reorganize it anyway or completely avoid those if it can detect constants being used or similar.
Organizing code can even give compiler hints of what is the likely/unlikely scenario and can optimize for that.
This is not as readable. Previous was simple to understand and most importantly debug. "If both conditions are true do this, else do that".
Now its "If this condition is not true do this, otherwise if the other condition is true do that". Not only while debugging you have to make more mental gymnastics, even saying it out loud makes it sound much more confusing that previous variation. Slight changes that may make the code seem smarter may make it really much more unreadable too.
If you'd say this to me, without showing the code, I'd write the "after" version, which is incorrect. The original is nowhere as simple: If first applies then if second applies do x else do nothing. If first didn't apply, then do y.
That's also gymnastics and likely the reason for the failed refactor because it still sounds a little ambiguous.
It's only natural to rephrase as: "If first doesn't apply do that, else if both apply do this" to fix the ambiguity. And the only change in this paraphrase is the order of conditions.
The original pseudo-code is also trimmed of any details, which would make seeing the flow harder. It also doesn't explain the empty else. Why nothing is done when only first is true?
I mean, the original code is complex, and I'd also refactor it so that nobody can repeat the mistake. Maybe the refactored version feels less readable to you, because you rephrased the original version way to simpler than it is.
I mean I guess. It’s just an obvious way to compact and to better prevent this issue from happening. I’m not saying it’s always the best thing to do. I replied to others to talk about that.
It looks like this comment contains a code block delimited with triple backticks. Unfortunately reddit does not have universal support for this syntax and your comment will not render correctly on old reddit and most mobile apps.
For the benefit of people on old reddit, this link will take you to a correct rendering of the comment.
/u/Franks2000inchTV, it would be appreciated, but not required, if you could edit your comment to use the more compatible four space indention format. For single lines or inline code you can use single backticks.
It looks like this comment contains a code block delimited with triple backticks. Unfortunately reddit does not have universal support for this syntax and your comment will not render correctly on old reddit and most mobile apps.
For the benefit of people on old reddit, this link will take you to a correct rendering of the comment.
/u/dyingpie1, it would be appreciated, but not required, if you could edit your comment to use the more compatible four space indention format. For single lines or inline code you can use single backticks.
It’s not just for a few lines. It’s so mistakes like this don’t happen. It’s important to fully understand the flow of the program. The way I wrote it is more explicit and is less likely to cause others to make this mistake. But also, it depends on the context, such as whether condition1 and/or condition2 are edge cases and whether the negation of condition1 makes sense.
Well at my college last year we had to write unit tests and our points were given by the ammount of unit tests we got green, but by those tests I mean ours and indeed, the unit tests for the unit tests. So it is possible.
I know it mainly from Rust, Julia also has macros for this via libraries, but as far as I know especially functional languages have had similar features for a long time. Haskell lets you do pattern matching right in the function definition/signature.
this is not equivalent code, condition2 is always evaluated
So? The intended behaviour is exactly the same, whether the performance is any different cannot be said beforehand because it heavily relies on the situation and used compiler/runtime. Lazy evaluation is not always better or faster.
readability can't be easily measured, it's all opinion. but some people value the low number of lines. in case one would choose this kind of code only for the lower number of lines, i just want to point out that it's more characters and imo character count matters much more
And did you really count characters in two pseudocode snippets?
i copy-pasted this into a text editor that can count characters
It doesn't need to come with a performance penalty I think. Anyway I think pattern matching will definitely be a must have for many future languages, and imho it's how switch-case should have been from the start.
In functional languages (and for people used to them) the pattern matching thing is more readable. If you used if statements in your haskell program then they would be considered less readable. All depends on what you're used to.
one of the below comments says to always add an else statement, I 100% disagree.
else statements are flow statements that increase the cognitive complexity of a statement and tie two conceptually unrelated concepts.
I think the problem is that people have tried to take advice that is good for on particular style of programming and to apply that advice to a very different approach to programming. Always adding an else statement makes a lot of sense if you're writing expression-oriented code, or more generally trying to keep your code as pure as possible and avoiding side effects. In that case, it makes obvious sense that every if should have an else because logically all branches should be pure expressions that return a value. In statement oriented languages you might end up using assignment to fake it (if(foo) { bar = 1; } else { bar = 2; }).
Of course, traditional statement oriented procedural programming this doesn't make any sense; an else is just syntactic sugar for if(condition) { statement1(); } if (!condition) { statement2(); }, and in this style of programming I agree with you- early aborting greatly eases the cognitive load on the developer who can flush their mental call stack as soon as you return, rather than accumulating the context of prior branches following down else branches.
It is, in the end, not so much a problem that the rules are wrong, but that people follow the rules without considering the context and end up misapplying them to situations they were never intended to address.
In a big fan of guard clauses. I find it helps readability and also gets you in mindset of ‘if I can exit early I should check for it to avoid running more unnecessary code’ thus improving performance.
The benefit of using else statements is that it forces you to think what should happen when the condition is not true.
For guard clauses this does not matter because you are already thinking about that: in case of error return early, and otherwise keep executing the function. In all other cases you should be using else clauses, even if it's just to add a comment like // otherwise, do nothing because we don't care.
Honestly the first one could be better. It's hard to see the intent, hence why it was refactored incorrectly and some people here missed the issue.
There's a couple of ways to make this better, but I'm not really sure which is best. Maybe check if both are true call "do anything one" , else if "condition one" is false then call "do anything two".
With real code it should be more obvious why you are doing that though it's still a bit of a head scratcher.
yeah, i usually blame myself and my code if a coworker comes along and refactors it incorrectly. the source code failed to do the one thing it's meant to do, communicate with other people.
and i usually consider it a good sign if they see it and understand it enough to make good, valid criticisms. then you know the code was legible, if suboptimal.
Yes; the "refactoring" changes what happens in that case, and could be classified as "did not read the code sufficiently well, introduced a bug" and also, "so ... is this covered by a test?".
I don't see why it needs refactoring. That being said, I think this is an easy mistake to make. Hope you have unit tests and a decent review culture that caught it.
I only started C++ a couple weeks ago and I have to say I probably would've made the same mistake.
For some reason I was thinking that the else statement would run if the nested if was false. I had to put this into the IDE cause I didn't believe it for a minute.
Oh don’t, I’ve just had to stop a second person from making a dumb change in code they haven’t taken the time to understand. They’re like “er this is doing way too much work, it should be much simpler” and then in the review I have to go “you fool, this will work for the absolute simplest case, but will break for literally anything more complicated”
Something similar happened to me last week and I was SO angry. My team is obsessed with making code look more “elegant” even if the solution has worse performance
As a rule of thumb, less nesting leads to better readability.
The original code quickly becomes hard to follow as the code block condition1 && condition2 grows. I also see a lot of devs forgetting to account for the missing else case. If you want to keep the nesting, you should at least put a comment for the missing else case:
if (condition1) {
if (condition2) {
// do something ...
} else {
// do nothing here, because ...
}
} else {
// do something else ...
}
Additionally, inverting the first condition is nearly always more readable.
if (!condition1) {
// do something else ... (usually an error case)
} else {
if (condition2) {
// do something ... (usually the happy path)
} else {
// do nothing here, because ...
}
}
But I usually end up refactoring my code to the following for optimal readability.
if (!condition1) {
// do something else (usually an error case)
} else if (!condition2) {
// do nothing here, because ...
} else {
// do something ... (usually the happy path)
}
It looks like this comment contains a code block delimited with triple backticks. Unfortunately reddit does not have universal support for this syntax and your comment will not render correctly on old reddit and most mobile apps.
For the benefit of people on old reddit, this link will take you to a correct rendering of the comment.
/u/paulsmithkc, it would be appreciated, but not required, if you could edit your comment to use the more compatible four space indention format. For single lines or inline code you can use single backticks.
do_anything2 should be executed if condition1 is false. In the refractored code it gets executed if condition1 is false OR condition2 is false. This means, do_anything2 can be executed if condition1 is true. Which clearly isn't what the first code intended.
It looks like this comment contains a code block delimited with triple backticks. Unfortunately reddit does not have universal support for this syntax and your comment will not render correctly on old reddit and most mobile apps.
For the benefit of people on old reddit, this link will take you to a correct rendering of the comment.
/u/oderjunks, it would be appreciated, but not required, if you could edit your comment to use the more compatible four space indention format. For single lines or inline code you can use single backticks.
I agree that the original code is good. I disagree that every conditional should have a comment. I would even say that the fewer comments you can get away with, the better. Obviously your code needs to be self explanatory by using well thought of names.
For example:
if (truckType == FireTruck) { setTruckColor(Red) }
No need to add comments, it's kinda obvious. I almost never encounter cases where comments are needed,I'm also always trying for ways to make the code self explanatory and readable, that's what I find most fun about coding anyway.
What the code does is self-explanatory, yes, but what it doesn't do is not, otherwise it wouldn't have been "refactored". The condition1 && !condition2 case isn't explicit, so if it's a case that's likely to come up, a comment would make sense.
I agree, else cases are more likely to benefit from a comment, but it obviously heavily depends on the actual conditions. And I still stand by my point that comments should be omitted if a good code structure makes them redundant, and that should be the goal to aim for.
Yeah, I was exaggerating a bit. Of course you're right, code should be obvious, but in reality it mostly isn't.
If you have to deal with tons of legacy libraries and convoluted names, commenting conditions really helps.
I also often have to write shell scripts, where if-conditionals might not be obvious for the untrained eye, especially if you have to use pattern matching and such. A comment helps very much.
While developing I often leave the code sections after an if-conditional empty at first and write a comment that shortly explains, why I did get actually there. Then I care about other conditionals. Then I fill the code sections. Then I refactor, but I tend to leave the comments in there, because it might help other people to follow my train of thought.
And I just apply the same commenting pattern to every programming language I'm using.
Assuming the code reviewer fucked up and you were right...
// Probably a cleaner way to do f_ptrs in C++? But this is fun
void foo()
{
void ( *anything_n )() = !condition1 ? &do_anything2 : ( condition2 ? &do_anything2 : NULL );
if( anything_n ) anything_n();
}
the code in the comment you're responding to does not do what OP's original code does. however, it is a valid use of the ternary operator. if do_anything1() and do_anything2() are non-void and their return types are compatible, then the operation will have a valid non-void result, but it doesn't have to be used. if both functions are void, then the operation is still valid:
If either the second or the third operand has type void, one of the following shall hold:
— The second or the third operand (but not both) is a (possibly parenthesized) throw-expression (8.17); the result is of the type and value category of the other. The conditional expression is a bit-field if that operand is a bit-field.
— Both the second and the third operands have type void; the result is of type void and is a prvalue. [Note: This includes the case where both operands are throw-expressions. — end note]
I forget where I read this, but it can be recommended to always have an else block for every if block, even if the else block is just empty with a comment. that way every possible case is clear
It looks like this comment contains a code block delimited with triple backticks. Unfortunately reddit does not have universal support for this syntax and your comment will not render correctly on old reddit and most mobile apps.
For the benefit of people on old reddit, this link will take you to a correct rendering of the comment.
/u/BearDavidFather, it would be appreciated, but not required, if you could edit your comment to use the more compatible four space indention format. For single lines or inline code you can use single backticks.
772
u/dyingpie1 Apr 17 '21
I would rewrite it as
34
u/Soliloquizing Apr 17 '21
How about:
171
u/SquidgyTheWhale Apr 17 '21
Yeah, but if he refactored the code this way, it broke your unit test, right? Right?
253
u/420TaylorStreet Apr 17 '21 edited Apr 18 '21
... sooooo, any unit test catch this?
279
u/naxxfish Apr 17 '21
This is when you realise that your fear of curly braces causes you to be dysfunctional ...
298
u/[deleted] Apr 17 '21
This is why I like languages with nice pattern matching, as it can often make code like this compact in a nice way. Something along the lines of
76
u/apieceoffruit Apr 17 '21
its funny for all the versions in the comments, I am surprised to see nobody has a version with a guard clause and no cyclomatic complexity:
Obviously the silly order dependent names make it more confusing. but a standard for this kind of thing is:
one of the below comments says to always add an else statement, I 100% disagree.
else statements are flow statements that increase the cognitive complexity of a statement and tie two conceptually unrelated concepts.
Instead, evaluate your "guard" statements, exit early if you can, so as you get down further the code gets simpler, not more complex.
instead of nesting in a tree of conditionals, knock down and remove ones you can evaluate early.
In fact Jeff Bay in his thoughtworks anthology book suggests his own rules for "object calisthenics" that includes never using the else keyword.
Not sure I subscribe to that one myself, but I do admit I don't use it very often. rarely does it make code easier to read.
34
u/gmtime Apr 17 '21
29
u/dgreenmachine Apr 17 '21
The code on the top is still super confusing and it makes sense to want to refactor it.
6
u/campbellm Apr 17 '21
Surely the unit test you have around it caught the logical error?
16
u/Eluvatar_the_second Apr 17 '21
Honestly the first one could be better. It's hard to see the intent, hence why it was refactored incorrectly and some people here missed the issue.
There's a couple of ways to make this better, but I'm not really sure which is best. Maybe check if both are true call "do anything one" , else if "condition one" is false then call "do anything two".
With real code it should be more obvious why you are doing that though it's still a bit of a head scratcher.
9
u/brakkum Apr 17 '21
I mean, yea they did it bad, but the original is also not the easiest to parse.
I'm not saying that's necessarily better, but it might be depending on what is actually going on in the code.
4
u/NetherFX Apr 17 '21
Could be wrong, but if condition1 is true and condition2 is false, then nothing would happen, right?
7
u/MurdoMaclachlan public boolean isInt(int i) { return true; } Apr 17 '21
Image Transcription: Code
I'm a human volunteer content transcriber for Reddit and you could be too! If you'd like more information on what we do and why we do it, click here!
3
u/[deleted] Apr 17 '21
I don't see why it needs refactoring. That being said, I think this is an easy mistake to make. Hope you have unit tests and a decent review culture that caught it.
2
u/musicianadam Apr 17 '21
I only started C++ a couple weeks ago and I have to say I probably would've made the same mistake.
For some reason I was thinking that the else statement would run if the nested if was false. I had to put this into the IDE cause I didn't believe it for a minute.
2
u/Biaboctocat Apr 18 '21
Oh don’t, I’ve just had to stop a second person from making a dumb change in code they haven’t taken the time to understand. They’re like “er this is doing way too much work, it should be much simpler” and then in the review I have to go “you fool, this will work for the absolute simplest case, but will break for literally anything more complicated”
4
u/bphase Apr 17 '21
Don't like the before either. Nested conditionals and the outer one does nothing. But yeah that's pretty embarrassing.
4
u/drea2 Apr 17 '21
Something similar happened to me last week and I was SO angry. My team is obsessed with making code look more “elegant” even if the solution has worse performance
3
u/Same-Impress-6899 Apr 17 '21
I would personally refactor it with a return statement, that takes care of the confusing else
2
u/ShewkShewk Apr 17 '21
This is what happens when code golf is prioritized over readability.
Not every refactor into sly code tricks means the code is better. Less readable code = harder to maintain.
1
u/Kazedy Apr 17 '21
That's why you have unit tests !
1
u/MCShoveled Apr 18 '21
It was definitely better before 😂
1
u/deadmazebot Apr 18 '21
Slap else with condition 3 and else if
1
u/nathan_lesage Apr 18 '21
Who needs condition1 either way?
1
u/rtzoor Apr 18 '21
This a good one
1
u/paulsmithkc 👨🏫 Apr 18 '21
As a rule of thumb, less nesting leads to better readability.
The original code quickly becomes hard to follow as the code block condition1 && condition2 grows. I also see a lot of devs forgetting to account for the missing else case. If you want to keep the nesting, you should at least put a comment for the missing else case:
Additionally, inverting the first condition is nearly always more readable.
But I usually end up refactoring my code to the following for optimal readability.
1
u/Tux1 Apr 18 '21
How is this bad?
1
u/futlapperl Apr 21 '21
I'm embarrassed to say that I've run into this before and spent a lot of time trying to figure out what went wrong.
1
u/feediza Apr 25 '21
That's why I always do the else case first.
if(!condition1)
{
x;
return;
}
if(condition2)
{
}
1
u/glorious_reptile May 09 '21
That’s close enough for government work.
1
u/FranticBronchitis Aug 03 '21
It took me too long to figure out what was wrong with that. That can't be a good sign.
1
u/GuyFawkes65 Oct 03 '22
Careful where you step… there’s bugs all over the floor
-1
u/[deleted] Apr 17 '21 edited Apr 17 '21
Edit: /s as some people though it was a serious attempt at improvement rather than an attempt to make it more hideous
1
u/harelavv3 Apr 18 '21
Wait... what's the problem with the second one? I don't get it...
0
u/valzargaming Apr 18 '21
-2
u/merdone Apr 17 '21
what's wrong with the refactored version? fewer ifs
0
u/admin_rico Apr 17 '21
Global conditions are the only conditions
-3
u/[deleted] Apr 17 '21
-1
u/oderjunks Apr 18 '21 edited Apr 18 '21
I dont see the issue
-6
u/kfl02 Apr 17 '21
The original code is good, except that comments are missing about the intent of every conditional branch.
I always write my code like this, because I might have missed something (like an "else" branch on "condition2" - yes, that often happens).
Cramming too many conditions into one "if" is bad.
If you really think that you have to combine conditionals, let your IDE do the work.
The compiler won't care anyway.
-3
u/[deleted] Apr 17 '21 edited Apr 17 '21
Assuming the code reviewer fucked up and you were right...
-5
u/KOTS98 Apr 17 '21
condition1 && condition2 ? do_anything1() : do_anything2();
0
u/[deleted] Apr 17 '21
[deleted] — view deleted comment
0
u/[deleted] Apr 17 '21
[deleted] — view deleted comment
0
u/[deleted] Apr 17 '21
[deleted] — view deleted comment
0
u/[deleted] Apr 17 '21
[deleted] — view deleted comment
0
u/[deleted] Apr 17 '21
[deleted] — view deleted comment
0
u/[deleted] Apr 18 '21
[removed] — view removed comment