DEV Community


Discussion on: 10 rules to code like NASA (applied to interpreted languages)

mikeschinkel profile image
Mike Schinkel • Edited

Based on your dislike of switches because they do not have intermediate ending braces, my guess is you really hate Python? #justasking

Thread Thread
xowap profile image
Rémy 🤖 Author

Oh no I love Python, actually it makes these rules easier to apply and also it does not have switch.

But it's about the confusing control flow rather than the syntax (which I really don't care about). Forget a break and you're toast. Stack cases and you're confusing anybody reading your code.

Thread Thread
mikeschinkel profile image
Mike Schinkel • Edited

Ironically just a few weeks ago I read an article by Dave Cheney — the bard of Go — entitled "Clear is better than clever" that advocates for using switch instead of if / else.

His article does mention that the switch in Go does not fall-through by default and your objection to the switch — which falls-through by default (a language decision I lament) — seems to be solely based on the potential to omit a break. But his article does give other reasons for switch to be superior to if / else none of which are mentioned in your post.

Personally, I think a belief that in-all-cases either if or switch is superior to the other is simply allowing oneself to overindulge in one's own unsubstantiated opinion.

(Notice I left off else; I concur with @DoMiNeLa10 and agree with the advice of Mat Ryer: Avoid else, when you can.)

Earlier this week I refactored some if / else code to be a switch statement in PHP. I did so thoughtfully and with the sole goal of adding clarity to the code someone else wrote who is no longer involved. The code was used to take action based on number of path segments in a URL. It had one if and three (3) else ifs where each condition tested count($parts) for equality with 1, 2, 3 or 4.

I needed to add logic for 5 so I changed from if / else if / else to a using a switch so the code would not need to call count($parts) five (5) times (nor need to set a temp var) and so that the logic was clearly spelled out that it was working on a use-case that had 1 of 5 options.

Further, when formatted the code was much more readable, the breaks were obvious, and the nature of the code meant it was unlikely someone would ever add both a 6 and a 7 and forget to include a break on the 6.

My point with this anecdote is that almost all coding "rules" really should be applied with an analysis of the use-case at hand and not be considered as a pedantic absolute. Clinging to dogma really does not benefit anyone.

Unless of course we are dealing with junior programmers, and then all bets are off. :-D