Writing Self-Confident Code

A common idiom in ruby is to call a method only if its receiver is not nil:

thing.foo if thing

or:

thing && thing.foo

Various libraries exist for making this a little more convenient. You can use andand, or if you are using Facets you can use ergo. And seriously, you should be using them — they make your code cleaner and more succinct.

But don’t let the existence of these libraries give you the idea that having null-checks throughout your code is OK. It’s not. Pervasive null tests are a code smell.

If you find you are using the elvis operator or its equivalent everywhere, you most likely have a design problem. Is it really OK for that attribute to ever be null? In a lot of cases the existence of a null attribute or association is indicative of an insufficiently specified contract. Maybe you should be setting that attribute to a default value at initialization, or requiring an explicit value for it at initialization. If it really is OK for that attribute to be null, consider whether you should be using a Null Object or some kind of default placeholder object rather than generic nil.

Checking for null is almost always an implementation detail, not a part of the domain you are modeling. As such the null check should be isolated to the boundaries of your code, or eliminated altogether. Code that constantly checks if things are null has an insecurity complex, always second-guessing itself. Make your code self-confident. Eliminate null checks wherever you can.