DEV Community

Alberto Forni
Alberto Forni

Posted on

Make Your Code Self-Documenting with Descriptive Event Handler Names

In software development, one of the key principles is to make code that is easy to read and understand. This is especially important in declarative systems like React, Vue or Svelte where the code describes what the system is supposed to do rather than the specific steps to do it. When you give your event handlers meaningful names, it becomes much easier for other developers (and yourself, when you come back to the code later) to understand the purpose of the handler just by reading the name.

For example, consider the following two event handlers:

// meaningful event handlers
<Touch
  onTouchStart={saveOffsetForMoveAndFocus}
  onTouchMove={moveWindow}>
...
</Touch>

// generic event handlers
<Touch
  onTouchStart={handleTouchStart}
  onTouchMove={handleTouchMove}>
...
</Touch>
Enter fullscreen mode Exit fullscreen mode

Which of these handlers is more meaningful? The first example clearly communicates what is supposed to happen, whereas the second one does not so, you need to browse the rest of the code to understand its purpose.

Using descriptive names for your event handlers makes your code more self-documenting, which can save time and reduce the need for detailed documentation. It can also make it easier to find and fix bugs in your code, as the names can provide clues about the purpose of the event handler and where it is being used.

Wait, this way my function names are gonna be too long!!!

When it comes to the length of method names, Uncle Bob suggests that it is generally better to err on the side of longer and more descriptive names, rather than shorter and more vague names. In "Clean Code" he writes:

"Don’t be afraid to make a name long. A long descriptive name is better than a short enigmatic name. A long descriptive name is better than a long descriptive comment. Use a naming convention that allows multiple words to be easily read in the function names, and then make use of those multiple words to give the function a name that says what it does."

To add to that, I recently came across a concept: the "Principle of Least Astonishment" or POLA, which states that code should be written in a way that minimises the surprise of the reader. I think that by giving your event handlers descriptive names, you can make it clear what they do and reduce the potential for a surprise when reading the code.

Top comments (0)