Explicit Plurality

Here’s a quick idea for making your code more readable.

In your code you want a method to get a specific user, getUser, but you also want a method to get all users, getUsers. These two functions will inevitably have different interfaces:

db.getUser(id); // id distinguishes this user from others
db.getUsers();

As a developer you spend a lot of time writing code, but even more reading it. While the distinction between User and Users is clear enough when writing it, it is easily overlooked when skimming through code. A mistake, such as leaving out a letter, can easily be overlooked because the reader expects the correct form to be used.

My colleague Asbjørn Thegler made the excellent point to me that there is a simple solution for this: be explicit in plurality.

This means writing getAllUsers instead of getUsers, lessening the similarity between the singular and plural forms, improving readability.

The distinction becomes even clearer in longer method names. Would you immediately be able to tell the difference between the following (hypothetical) method?

db.getActiveUsersWithComments(filter, callback);
db.getActiveUserWithComments(id, filter, callback);

Imagine them not being placed right next to each other for easy comparison. That little s is hard to spot. Here’s a slightly more distinguishable one:

db.getAllActiveUsersWithComments(filter, callback);

There are some cases of plurality (person -> people, for example) that are easier to spot. For consistency, I would recommend including the word all anyway.


When I write more, filling out this form will let you know.

 
3
Kudos
 
3
Kudos

Now read this

Stagnation and Tunnel Vision

It is easier to learn when you are young. So I have been told all my life. According to research on neuroplasticity the brain continues to grow and learn from what it is exposed to—it never stops. As we get older, life is filled with... Continue →