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

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.


Now read this

Group Flow in Software Development

In The Clean Coder, Robert C Martin writes about being in the Zone: Let me be clear about this. You will write more code in the Zone. If you are practicing TDD, you will go around the red/green/refactor loop more quickly. And you will... Continue →