POSTS
Code Style: If and return
By Carlos Buenosvinos
- 1 minutes read - 209 wordsWhen contributing to opensource code at GitHub, I found some mistakes, or improvements when writing code, that are repetead over and over again for newbies and not so newbies developers. I’ll try to write some posts about this, but for not, let’s start with some “if” and “return” statements cases.
Return #1: If + big code + small else
When you have and if-else, I’d prefer to have the shortest block first so I can see more information at once. Specially, the first flow related with the conditional cases.
Bad:
Better:
Return #2: If + return + useless else
If you return something in the first case, “else” is useless. Removing it reduces lines of code, cyclomatic complexity and so on.
Bad:
Better:
Return #3: If + return true + else return false
I don’t know why, but this is typical. If you are returning booleans, please, return the conditional evaluation.
Bad:
Better:
Return #4: If + return A + else return B
Exactly the same with other types.
Bad:
Better:
Return #5: If + else that holds a default value
One variation for case #2.
Bad:
Better:
Feel free to comment for adding other examples that may help others. Please, make your mates live easier. Happy Clean Coding!