I won’t argue how cool and handy “safe navigation” is but rather I want to warn you that overconsumption of it may lead you to the dead end… – Just like other bad habits. Where you are going to be trapped in your own code base is associated with “what the heck is wrong with it?” enigma.

Of course, we know that safe navigation can help you to avoid cases mentioned in the article here. You don’t need to check whether an object responds to the amount method. And we finally can use something instead of “try” method that comes with ActiveSupport in a nice package. Just give the code “&” symbol like in the example below and you are good to go.

2.3.1 :014 > @transaction&.amount.to_f
 => 0.0

The example above is a sort of shorthand for

(@transaction && @transaction.amount).to_f

But what if the object was never meant to be nil? For instance, the object has never been found because along with the previous commit you introduced some bug which drove you to the case of getting NilClass instead of raising an error?

It is indeed astonishing that instead of throwing an error the program continues its execution. Nevertheless, if I’d be Debbie Downer here I should say it also can create additional overcomplexity to spot a bug. You won’t get any exception if something is broken or missing as time flies.

It’s nice to keep in mind that sometimes we rather want the exception to appear in the log than just silently ignore it and postpone first disease symptoms.

I personally think it’s better for the customer to get an engaging error instead of leaving him with a strange effect of full unknowingness.187

And by the way, as I said – it is possible that you can easily get lost in your own codebase if you will use safe navigation too much, which sometimes has some similarities with throwing out the ball of thread in a Labyrinth.

If something is missing it would be a lot easier to fix it in the first place using something like errbit instead of escaping it and trapping yourself into the puzzle.

So all in all, you have to use it carefully.

What are your thoughts, though? Leave the comments below.

One thought on “Lonely Operator, eh?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s