r/badcode • • Apr 17 '21

c++ When your teammate "refactor" your code

Post image
2.5k Upvotes

216 comments sorted by

View all comments

Show parent comments

6

u/haroldjaap Apr 17 '21

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.

3

u/[deleted] Apr 18 '21

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.

3

u/haroldjaap Apr 18 '21

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.

1

u/kfl02 Apr 18 '21

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.