How do I name my object when it’s related to other objects?

Given that we know we should add a sensible naming protocol to our objects, sometimes we have to decide what the best name for an object will be.

In most apps you often end up with objects that only make sense in the context of other objects.

Take the following classes – a Product connects to an Assembly via a Connector. The names for the Product and Assembly are pretty straightforward, but the Connector only makes sense in the context of the other two. (It’s a Rails example, but the principle applies everywhere).

There’s a problem with the definition of to_s on Connector though.

What if @connector.product or @connector.assembly is nil?

A big fat error – undefined method name for nil:NilClass!

You may think – well, I’ll just stick validates :product, presence: true and validates :assembly, presence: true on my Connector and I’ll be safe.

You may think that, but you won’t be safe.

One rule of production apps is if something can go wrong it will. And there will be a case where the product is nil – maybe the associated product record got deleted, or someone ran a rogue script on the database that filled it with nulls.

It’s a big bad world. Anything could happen.

And you don’t want your app showing a sobbing 500 error page.

Luckily, proper use of to_s makes it easy to deal with this. Change the implementations to look like this:

Because everything has a to_s method and we’re using them in our string, it doesn’t matter if one is nil – nil.to_s is just a blank. So we’re using Ruby’s dynamic nature to save us from ourselves.

Do you know what to do but not how it works?

Ever wanted to understand why Rails views work the way that they do? Why variables from your controllers are visible inside your views?

Sign up below to get a free 5 part email course on how Ruby on Rails view rendering works and gain a deep understanding of the Rails magic.

We will send you the course, plus the occasional update from this web-site. But no spam, we promise, and it's easy to unsubscribe