Better Naming Practices

Since code is read many times more than is written, then code readability becomes of extremely high importance among developers. Naming among other readability factors becomes the coder’s crucial task that needs more attention and scrutiny.

The following is written from personal views and readings in form of tips and/or suggestions with hope of illuminating this topic from angles that you might have not been considered before.

Tips / Suggestions

Variables are usually data containers. So, in case the contained data is quantifiable try to be clear about what is the content what is its unit of measurement.

1
long intervalInMillis = 3500;

A kind of poor variable names are those abbreviated Unix names since they are usually mis-informative.

1
2
3
String cd;
int sco;
double ps;

It would be much better not to use the postfix ‘List’ on variable names containing a group of objects unless they are actually based on list data-structure.

1
2
Employee[] employeeList;
HashTable<String, Device> deviceList;

Using single letter names might be alright for short loops and small scopes but even in that case it can exponentially get harder to understand as it gets more complex; Moreover, they can also be severely hard to track throughout wider scopes. In the for-loop example below although the logic is cramped into one line, still variable names play a crucial role in crunching the knowledge there.

1
2
3
4
5
int l = 1, O = 0;
for (int j=0; j<34; j++) {
s += Math.pow(t[j/Math.round(x/5.5)]*35.7)/5;
}

Additionally, although today’s IDEs are quite advanced to find all usages of a variable or method, yet choosing a very popular and common name could still prevent developers from rapidly tracing them. Imagine if all loops were about to use ‘i’ as the loop variable throughout a relatively large code base, then guess how many search hits we will get if we’re about to look for a specific one.

1
for(int i = 0; i < ...; i++)

A rule of thumb is that shorter names are usually better than the longer ones; however long and similar names are always ambiguous and hard to distinguish and can become points of mistakes.

1
2
Handler CustomerOrderHandlerForIncomingQueuedOrders;
Handler CustomerOrderHandlerForIncomingStoredOrders;

using prefixes such as ‘a’ or ‘the’ could be helpful if they convey the true nature of the variable.

1
2
3
4
5
Person thePerson;
for (Person aPerson : personnel) {
if (person.id() != id) continue;
thePerson = aPerson;
}

Use names that are easily pronounced. They will ease communication about the code with other developers and they are easier to remember.

1
2
Employee rchAndDevDepMngmt;
Handler httpWsWsdlSoapMsgHndlr;

Another bad naming habit is encoding variable types into their names. In a strongly typed language like Java, developers are inevitably presented with the variable type; as a result, adding type to variable names is both redundant and misleading after future refactoring.

1
2
3
String ipAddressString;
// what if IpAddress is later on moved into its own class as below?
IpAddress ipAddressString;

I guess this one is mostly a matter of developers taste but I’ve seen conventional prefixes/suffixes (such as Android ‘m’ prefix for member variables or ‘_‘ prefix in C# for the same reason) that never earned importance in code clarity in my personal view.

Adding a couple of ‘this’ keywords might not affect coding time or the readability, but those prefixes/suffixes will gradually become clutter over time as they don’t play a crucial role in code clarity.

1
2
3
4
5
6
7
8
9
10
11
12
public class Person {
private string _name;
public string Name {
get { return _name; }
set { _name = value; }
}
public Person(string name) {
_name = name;
}
}

However, I personally adapted some of them such as “adding ‘I’ prefix to indicate an interface” soon after learning and finding out their benefits. Well, The fact that interfaces in each namespace are grouped together and that a class can be distinguished from its interface by a quick glance to the IDE’s explorer view is very convincing for me. Additionally, this keeps the original name reserved for the probable abstract class which implements common functionalities for the family. But then again, some consider this prefixing redundant; as uncle bob states in his book ‘Clean Code’:

Leave interfaces unadorned.

If possible, do NOT use verbs for class names and as for method names, you may usually want to start them with a verb. Look how the following snippet easily conveys its intent.

1
2
orderService.process(order);
mailClient.sendConfirmation(message, recipient);

While choosing method names, try to be meticulous about informing its true intent. An action that in the first glance seems like ‘add’, might indeed be an ‘append’, ‘insert’ or ‘concatenate’. Moreover, choose consistent words for same behaviors; meaning that, for a ‘get’ action, always use one of the phrases ‘get’, ‘fetch’, ‘receive’ or ‘retrieve’ all the time.

In case of having overloaded constructors in your class, prefer the use of static factory methods that are named after received arguments and already hands more information. Accordingly, a class like this:

1
2
3
4
class Point {
Point(double x, double y) {...}
Point(double radian, double distance) {...}
}

might be more readable during instantiation with the following static factory methods.

1
2
3
4
5
6
7
8
9
10
11
12
class Point {
private Point(double x, double y) {...}
private Point(double radian, double distance) {...}
public static inCartesian(double x, double y) {
return new Point(x, y);
}
public static inPolar(double radian, double distance) {
return new Point(radian, distance);
}
}

If at all possible, avoid mentioning customer/company names.

1
2
class CompanyAbcSelector {}
void companyXyzSort(Collection items) {}

instead try to come up with design pattern names, known algorithms names or famous mathematical terms.

1
2
class CellSelectionStrategy {}
void quickSort(Collection items) {}

Conclusion

A quality code should be able to easily convey the flow of logic to the reader and shall not require any additional descriptions. Code is dynamic, changes and improves over time while comments are usually forgotten and rarely updated. Accordingly, use of proper descriptive naming greatly helps eliminating the need for comments and allows the code to narrate itself.

Use names that reveal the true purpose behind what the logic is supposed to serve which in turn will result into more readable, understandable and more manageable code.

Share Comments