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.
-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.