this post was submitted on 02 Feb 2024
295 points (96.8% liked)
Programmer Humor
19695 readers
141 users here now
Welcome to Programmer Humor!
This is a place where you can post jokes, memes, humor, etc. related to programming!
For sharing awful code theres also Programming Horror.
Rules
- Keep content in english
- No advertisements
- Posts must be related to programming or programmer topics
founded 1 year ago
MODERATORS
you are viewing a single comment's thread
view the rest of the comments
view the rest of the comments
The code in the image is C or C++ or similar. In those languages and languages derived from them, curly braces are optional but the parentheses are required. It should be the other way around to avoid logic errors like this:
Based on the indentation you’d think that
doSomethingElse
was only meant to run if theelse if
condition was true, but because of the lack of braces and theprintf
it actually happens regardless of either of theif
conditions. This can sometimes lead to logic errors and it doesn’t hold up to a principle of durability under edit — that is, inserting some code into theif
statement changes the outcome entirely because it changes the code path entirely, so the code is in a sense fragile to edits. If the curly braces were required instead of optional, this wouldn’t happen.I have all of my linters set up to flag a lack of curly braces in these languages as an error because of this. It’s a topic that sometimes causes some debate, ‘cause some people will vociferously defend their right to not have the braces there for one liners and more compact code, but I have found that in general having them be required consistently has led to fewer issues than having arguments about their absence, but to each their own. I know many big projects that have the opposite stance or have other guidelines, but I just make ‘em required on my own projects or projects that I’m in charge of and be done with it.
That makes perfect sense, thank you.