DEV Community

András Tóth
András Tóth

Posted on

Why is good naming so important?

I started to feel bad about torturing my fellow colleagues to have better function, variable and class names and also easy to understand error messages.

If you can think of good names for every piece of your code I believe that you also understand the domain of the problem, that you can deconstruct a problem to a logical set of low-noise actions.

I will also think that you will be able to explain what you are working on or struggling with to your colleagues - which is also super important in a workspace.

So by spending time on naming your variables, functions and classes you also have to think on a higher level, mapping out what you are really doing by verbalising it. And that is a great detector of uncertainty and half-baked ideas.

Therefore it is a good practice to stop time-to-time before you create a pull request to look what you already have and find the most descriptive names possible. When you learn more about a programming language you will be able to use more syntactic solutions to increase the readability of your code.

Examples

Super generic name

import { hosts } from 'config';

export function serverhost() {
  return hosts[1];
}
Enter fullscreen mode Exit fullscreen mode

Is it an action to host a server? A variable that return a hostName of a server? Is the returned value host an object maybe which has IP address as well? Why do you return only the second one?

Does way too many things

import { server } from 'my-fav-server-lib';

export function getHostNameAndLogErrorAndSetItAsWellIfItIsNotDefinedAlsoStartServer() {
  const hosts = server.getHosts();

  if (hosts.length === 0) {
    hosts[0] = server.start().getDefaultHostName();

    console.error('Hosts was empty! Starting a new server instance.');
  }

  return hosts[0];
}
Enter fullscreen mode Exit fullscreen mode

Why are we starting a server in a getter? Why are we getting its host name?

Summary

Exercise your mind by naming things well and do not be afraid to split and reorganize code if you struggle to find a good name. I do it very often: "Oh, now that I know what I want from this code let's split this function up!". After you did your best it is time for your colleagues during a pull request to help you finding the words that work for all of you! 😊

Top comments (0)