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.

 
4
Kudos
 
4
Kudos

Now read this

Software Is Never Finished and Code Can Always Be Improved

“Software: never finished, only abandoned,” John Saddington paraphrased Leonardo da Vinci, around a year ago, in the best blog post I have found for the well-known adage “software is never done”. Where it actually originated I have no... Continue →