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

Web apps: validate, delegate, respond

Web apps should be a thin, easily replacable front to your business logic. It should be modular and composable. I have written about this before. But how do you — in practice — decouple the business logic from the web frontend? I like to... Continue →