top | item 25786956

Structured programming: how to write proper if statements

4 points| harporoeder | 5 years ago |boris-marinov.github.io | reply

3 comments

order
[+] redwolf22|5 years ago|reply
I disagree. Using this technique will lead to more cyclomatic complexity. I aim to write small methods and readable code. In small methods, there is no problem using early returns. Early returns will also help in the readability, because you can stop reading as soon as you realise, that the method returns here, whereas you have to read the whole method in order to know if some other code is executed.
[+] swaranga|5 years ago|reply
My take on such “rules” is that these are not really rules but guidelines you can take hints from to make code easier to read and understand. I rarely try to force these rules to my code whether I am writing new code or changing existing code. Sometimes breaking these rules will make it better, and sometimes enforcing the rule will make it easier to read.

My process is to write the code, take my hands off the keyboard and just read it. Take a break and come back and read it again. Then upload a code review request but before you “publish” it for review read it in the browser again and makes changes as you see fit. This applies to design patterns as well. To me it is always circumstantial and should not feel forced. Sometimes the inherent nature of the logic requires me to keep all the conditionals together in a tight method with good documentation to make it easier to read it a year later. Sometimes it just “feels” cleaner to split it out. It always depends.

[+] Kim_Bruning|5 years ago|reply
Lots of extra comments here:

https://lobste.rs/s/z17zyg/structured_programming_how_write_...

Like several of the commenters there, I also think that early returns are actually a good pattern. (I also happen to think that throw and yield are perfectly fine. )

If you know that your method is never going to work out anyway today, abort immediately. Don't hang around!