DEV Community

Discussion on: Is “Defensive Programming” actually healthy?

Collapse
 
mortoray profile image
edA‑qa mort‑ora‑y

Defensive programming is a must if you wish to obtain high-quality software. The main thing it does it stop bugs from propagating far through the code.

Your example is a complex one, because it depends a lot on the language. There are numerous simpler examples that can demonstrate the value of defensive coding. That is, just because there are situations where it may not be warranted, doesn't mean it isn't warranted as a whole.

Checking enums via if's is generally the wrong thing to do. If you intended to cover all cases than some kind of switch is expected -- which then many languages will catch new conditions being added which aren't covered. If the language does not support a switch statement, then having a catch-all final case is the only sane option. This is because a series of if-else conveys a different meaning than a switch statement, but you actually intended to have a switch statement.

Collapse
 
cubiclebuddha profile image
Cubicle Buddha

A lot of people avoid switch statements since it’s too hard to enforce good behavior like avoiding fall through. But I get your point.

Collapse
 
mortoray profile image
edA‑qa mort‑ora‑y

Not all languages are broken like classic C. Even C/C++ compilers can provide warnings on fall-through and missing case's now. Using those languages without warnings turned on, and heeding all warnings, is crazy.

C# requires full coverage I believe.

Thread Thread
 
cubiclebuddha profile image
Cubicle Buddha

Two points of correction/clarification:
1) the solution I provided in the article works for switch statements too
2) the solution I provided gives you feedback at compile time. C# would only help you out at runtime. See here: stackoverflow.com/a/20759116/706768

Thread Thread
 
mortoray profile image
edA‑qa mort‑ora‑y

Oh, I didn't mean to imply there's something wrong with your approach, only that there are simpler cases to convince people of the need for defensive programming. Your solution is fine for the languages you're using.

Hmm, I wonder what language it was, if not C#? I recall one of them would produce an error (and of course C++ with the warning enabled).

Thread Thread
 
cubiclebuddha profile image
Cubicle Buddha • Edited

Point taken. As for your question, I’m not sure which language besides TS supports checking exhaustiveness. Btw, I had copied the gist link incorrectly in the solution part of the article. You can now see the use of the never type. Woopsie!

Thread Thread
 
pitweetie profile image
Andy Lamb

@edA-qa, in the .Net world are you thinking of F# maybe?