DEV Community

Discussion on: Is “Defensive Programming” actually healthy?

Collapse
 
johncip profile image
jmc • Edited

One thing that's informed my thinking about this is a talk where Rich Hickey discusses the relative badness of software problems. The big ones are he calls "problems of misconception," and are closer to the domain or architecture. The small ones are things like typos, naming, formatting, etc. The small ones are easy to fix; the big ones are orders of magnitude more dangerous.

We'd love to guarantee that certain things can't happen at runtime, so that we'll have less to reason about. The guarantees usually require adherence to some discipline, like design-by-contract, static typing, or avoidance of language features (e.g. no switch without break). But we should weigh the behavior's badness (and likelihood) versus the cost of prevention.

Also, no one's perfectly defensive. For example, occasionally one needs multiple dispatch. Yet most programmers don't insist on sticking to the handful of languages that offer it. Do you?

We're all happy to say YAGNI when we perceive the costs.


it costs almost no time to add exhaustive type checking to your code

Static type checking has its benefits, of course. But annotating isn't where the true cost lies. Instead, it's:

  • A lack of flexibility around data structures (when the shape changes, you have more code to update).
  • Less algorithm reusable, as code is usually tied to some type. At the very least, making it reusable takes more work.
  • Often you only deal with a subset of some aggregate structure. You can anticipate that with Options / Maybes / etc., or else allow null to propagate, which is type safety theater. (Though I've heard that TS has row polymorphism and I'm interested to see how much it helps.)
  • The more dynamic you want to be, the more elaborate the type system has to be. Past a certain point, you're just prevented from writing those things.

The good news is, type checks are always on; you can't neglect them. And the cost of annotation is low for most functions.

The bad news is that type checker can only guarantee a narrow set of things. It guarantees them all day long, but that's only because they're the things that are easy to check. What are the chances they're also the things that you truly care about?