Abandon Composed Names

Extract meaningful objects or methods out of composed name unless they're part of the domain's language

First, what do we mean by Composed Names ?

  • paperBag

  • userAge

  • movementSpeed

  • weekEnd

Some of these words are inevitably composed and have an inherent meaning such as paper bag and week-end.

But some others...

Revealing Objects

Why do we need a userAge variable ?

Wouldn't it be more logical to simply have a User object with a method to get their age ?

Also, what do we want to do with that user's age ? Are we getting this information to output it somewhere out of the system, or are we making decisions out of it ?

In the last case, you're definitely not thinking object.

But in any case, having to specify userAge either means...

  • The method deals with other informations related to the user, in which case it makes even more sense to group these informations into a single object

  • Or the method deal with the age of other things or other people, in which case it'd be more elegant and respectful to have these two objects communicate their age or perform actions based on the age without controlling them

Our sole responsibility as object thinkers is to make object communicate to one another, something like a mediator.

Not to work for them like a janitor.

The same thinking goes for movementSpeed. I'm sure there's more to a movement than its speed. A movement usually also have a direction. Hence, it's an object.

Scopes

Last, but not least, if you don't believe there's a proper reason for another object, at least think about the scope of your method.

If you need such composed names, your method probably does too much.

As Robert Martin (and others before him) says in his great book Clean Code, the name of the variables grows proportionally to the scope of the method.

The larger the scope, the longer the name of the variable. The smaller the scope, the smaller its name.

It's logical : you need to use prefixes and composed names to give more context to a variable.

The same way you need a first name and a last name because there's hundreds of Mary & Joe out there you need to distinguish yourself from.

Ideally, this context is in the form of an Object. That's what objects are for.

When that's not the case, that context is in the form of a method. So method extraction is one very useful technique to still disrespect objects but in an acceptable way.

Last updated