Naming Advice – A Rule

Consider this:

If you have to write a comment in your code is it because you haven’t named your variables or functions well? I very very many cases the answer is yes.

Here’s a simple example

Consider the case of a control system for a passenger lift in a tower block. You have some digital inputs in a class called DigitalInputs and this has a series of functions to get the values of the inputs wired to input pins on your hardware. Lets suppose your software wants to check if the doors of the lift are safely closed (if they are the software may then start to move the lift to a different floor).

If the door is closed limit switch is wired to pin 16 for example your code might be:

if (DigitalInputs.Pin16IsActive()) {
// … your code to start the lift moving goes here
}

At a later date you may think this is not particularly well written so you choose to add a comment:

if (DigitalInputs.Pin16IsActive()) /* check the door is closed */ {
// … your code to start the lift moving goes here
}

This is clearer than the first sample. But a much better improvement is not to add the comment but instead to rename the member function Pin16IsActive() in class DigitalInputs to a better name, for example LiftCabDoorIsClosed(). The code then becomes much more readable (without comments)

if (DigitalInputs.LiftCabDoorIsClosed()) {
// … your code to start the lift moving goes here
}

The big bonus is that now, everywhere this function is called throughout the code, it is clear what is being checked.

Naming rule: If you have to write a comment in your code think to yourself “is it because a variable or function is badly named?”