How To Be Great At Giving Meaningful Names

Vimox S Shah
Shipmnts
Published in
6 min readOct 8, 2018

Why meaningful Names?

  • Consider you are naming a child (sounds too easy right?)
youAreMyKid(), cuteLittleBaby(), shyBaby()
  • I guess you would want to consider those names.

There are only two hard things in Computer Science: cache invalidation and naming things — Phil Karlton

We tend to form identities, store and retrieve related information about places, people things basis on their names. Similarly, names are everywhere, even in the smallest bit of code we write. We name our variables, functions, arguments, classes, and packages.

We name our source files and the directories that contain them. If the names don’t reveal the right intentions, are not distinct and are not easily recallable readability of the code decreases drastically. In this article, I will try to share my learnings from Clean Code by Robert C Martin. What follows are some simple really good conventions for giving proper names in our code so that we avoid confusing situations like who was John The Third and who was John The Third Junior?

One difference between a smart programmer and a professional programmer is that the professional understands that clarity is king. Professionals use their powers for good and write code that others can understand — Robert C. Martin

Use Intention-Revealing Names

The name of a variable, function, or class, should answer all the big questions. It should tell you why it exists, what it does, and how it is used. If a name requires a comment, then the name does not reveal its intent.

Bad

int d; // elapsed time in days//The name d reveals nothing

Clean

int elapsedTimeInDays;

Can you tell what is the purpose of below code? Think for a minute

def get_them() list1 = [] the_list.each do |tl|   if tl[0] == 4    list1.push(tl)
end
end return list1
end

Questions:

1. What kinds of things are in the_list?

2. What is the significance of the zeroth subscript of an item in the_list?

3. What is the significance of the value 4?

4. How would I use the list being returned?

The answers to these questions are not present in the code sample, but they could have been.

Avoid Disinformation

Programmers must avoid leaving false clues that obscure the meaning of the code. Using inconsistent spellings is disinformation don’t refer the list of sales invoice to sales-invoice-list. instead use bunchofsalesinvoice, salesinvoices or salesinvoicegroup

One more form of Disinformation in names would be the use of lower and upper case in combination. If you follow camelCase go camelCase convention. but don’t mix and match i.e SalesInVoice, SavingAccOunt etc.

Make Meaningful Distinctions

You shouldn’t use the same name to refer to two different things in the same scope. you might be tempted to change one name in an arbitrary way.

Noise words are a meaningless distinction. For example, imagine that you have a Product class. If you have made one more class with a called ProductInfo or ProductData, you have made the names different without making them mean anything different. Info and Data are indistinct noise words like a, an, and the.

Distinguish names in such a way that the reader knows what the differences offer. moneyAmount is indistinguishable from money, customerInfo is indistinguishable from customer, accountData is indistinguishable from account

Use Pronounceable Names

Easily pronounceable names are easily recallable. If you can’t pronounce it, you can’t discuss it without sounding like an idiot

Compare

class DtaRcrd102 {   private Date genymdhms;   private Date modymdhms;   private final String pszqint = ”102”;   /* … */};

to

class Customer {   private Date generationTimestamp;   private Date modificationTimestamp;   private final String recordId = ”102”;};

Use Searchable Names

Searching variables by name in a huge code base is a frequent thing for programmers while they are debugging or trying to trace where all that variable, class or function is being used. Single-letter names and numeric constants have a particular problem in that they are not easy to locate across a body of text. Avoid using them.

Avoid Encodings

Encoding type or scope information into names simply adds an extra burden of deciphering it and adds cognitive friction in remembering it. It hardly seems reasonable to require each new employee to learn yet another encoding language in addition to learning the (usually considerable) body of code that they’ll be working in.

Avoid unnecessary encodings of datatypes along with the variable name.

String firstNameString; Float weightFloat;

It may not be necessary where it is very well known to the entire world that in a user context, the first name is going to have a sequence of characters. The same goes for Weight, which is decimal/float.

Avoid Mental Mapping

Collaborations happen quite often when the different teams are building separate modules of the same product. When someone new or from other team is reading he/she shouldn’t have to mentally translate your names into other names they already know. This is a problem with single-letter variable names. Certainly, a loop counter may be named i or j or k (though never l!) if its scope is very small and no other names can conflict with it. This is because those single-letter names for loop counters are traditional.

Bad

locations = [‘Austin’, ‘New York’, ‘San Francisco’]
locations.each do |l|
do_stuff
#do_some_other_stuff
# other stuff
# Wait, what is `l` for again?
dispatch(l)
end

Clean

locations = [‘Austin’, ‘New York’, ‘San Francisco’]
locations.each do |location|
#do_stuff
#do_some_other_stuff
# ..
dispatch(location)
end

Class Names

Classes and objects should have noun or noun phrase names like Customer, WikiPage, Account, and AddressParser. Avoid words like Manager, Processor, Data, or Info in the name of a class. A class name should not be a verb.

Method Names

Methods should have verb or verb phrase names like postInvoice, deleteShipment

Pick One Word per Concept

Pick one word for one abstract concept and stick with it. For instance, it’s confusing to have fetch, retrieve, and get as equivalent methods of different classes. How do you remember which method name goes with which class? The function names have to stand alone, and they have to be consistent in order for you to pick the correct method without any additional exploration.

Bad

user_info
user_data
user_record
starts_at
start_at
start_time

Clean

user
start_at

another example

dataFetcher() vs dataGetter() vs dataRetrieval()

If all three methods do the same thing, don’t mix and match across the code base. Instead, stick to one.

Use Solution Domain Names

Remember that the people who read your code will be programmers. So go ahead and use computer science (CS) terms, algorithm names, pattern names, math terms, and so forth.

It is not wise to draw every name from the problem domain because we don’t want our co-workers to have to run back and forth to the customer asking what every name means when they already know the concept by a different name.

The name AccountVisitor means a great deal to a programmer who is familiar with the VISITOR pattern.

Use Problem Domain Names

When there is no “programmer-eese” for what you’re doing, use the name from the problem domain. At least the programmer who maintains your code can ask a domain expert what it means.

If you master removing duplication and fixing bad names, then I claim you master object-oriented design — J. B. Rainsberger excerpted from The Four Elements of Simple Design

Add Meaningful Context

There are a few names which are meaningful in and of themselves — most are not. Imagine that you have variables named firstName, lastName, street, houseNumber, city, state, and zip code. Taken together it’s pretty clear that they form an address. But what if you just saw the state variable being used alone in a method

You can add context by using prefixes: addrFirstName, addrLastName, addrState, and so on, Of course, a better solution is to create a class named Address

Writing clean code is an art and it requires practice, a lot of it.

Conclusion

The hardest thing about choosing good names is that it requires good descriptive skills and a shared cultural background. This is a teaching issue rather than a technical, business or management issue. No one is good at naming especially when you’re hurrying upon to meet the deadline.

People are also afraid of renaming things for fear that some other developers will object. We do not share that fear and find that we are actually grateful when names change (for the better)

So, set up your naming convention soon if it’s still not in place and churn clean code. Happy Coding!

--

--