Ruby’s Lonely Operator or Safe Navigation Operator

Poking through some Pull Requests I spotted syntax I’ve never seen before and found difficult to google:

person&.job&.company&.id

The “&.” was introduced in Ruby 2.3.0 as the Lonely Operator. It prevents the error “NoMethod error on Nil”. If the object is nil it just returns nil. Otherwise it continues down the chain and gives the intended result.

This allows us to skip the heavy handed code of

person && person.job && person.job.company && person.job.company.id

Using the Lonely Operator looks better. It does have valid criticisms against it. First, it doesn’t address the original issue: having a null object when you weren’t expecting it. A reliable and recommended solution is the Null Object Pattern.  An author by the name Franzejr has a clear Ruby implementation of the Null Object Pattern.

Second, this encourages us to violate the Law of Demeter.  The problem of getting a persons company id is the tight coupling between those objects. This increases the cost of maintenance and chances for technical debt.

I’m curios to see where the Lonely Operator goes. I’m happy to have it in my tool belt. It simplifies chaining multiple methods. It accommodates legacy code where the Null Object Pattern may complicate a code base further.

While researching Ruby’s Lonely Operator I found the following articles helpful:

Let me know what you think in the comments. I’m curios how often you find the Lonely Operator in the wild and if you use it.