Good naming for a beautiful code

Naming variables, methods and classes well helps teammates to easily understand your code. Indeed when a code is perfectly named you feel like almost reading english. Thus, it’s not necessery to read the documentation or the code of a method to understand what it does. It saves a lot of time and makes developers happier. I am going to explain how I try to choose a good name when I am writing Ruby.

First I use a kind of grammar for naming variables, methods and classes. I use regular names for classes and variables. I start all my methods by a verb except when it’s an attribute accessor. When choosing a verb, I avoid to pick up set and get, because they are catch-all. Let’s take an example with a server instance providing data.

server.data        # Read an attribute?
server.get_data    # Better but still bad
server.fetch_data  # Good name, I understand it goes through the network

It’s pretty clear that the last example is the most explicit naming. Indeed, I understand it retrieves data from the network, so it is explicit that call could be slow. However don’t go too deep in detail. If the name expose all the internal behavior and algorithme, then you went too far. When calling a method, we are interested by its result, not how it has been implemented.

server.fetch_data_via_http # Callers usually doesn't care about internal behavior

It’s also important to be consistent. Let’s say you have a cart object and the payment process has two steps. First it initializes the payment, then it confirms.

# Not consistent, because the calling order is not obvious
cart.authorize(...)
cart.purchase(...)

# Consistent naming, because it makes clear that those methods are linked
cart.prepare_checkout(...)
cart.complete_checkout(...)

For variables I don’t prefix or suffix them with their type, because it generates noise. Most of the time names is connected to the variable type. I try to be accurate about the naming. If the code is dealing with a banned user I name it banned_user instead of just user.

Arguments order must not be disregarded. I use to put the most important argument in first, because it is directly related to the verb used by the method.

 # Which one makes more sens?
email.send_to(headers, users)
email.send_to(users, headers)

I try to avoid boolean parameters because they don’t have any sens when written litteraly.

# What means the last argument?
email.send_to(users, headers, true)
email.send_to(users, headers, signature: true)

I hope those small tips have been interesting.


Home