Y.Alouani

How to Name Your Code: A Guide to Meaningful Naming

๐‚๐ฅ๐ž๐š๐ง ๐‚๐จ๐๐ž ๐’๐ญ๐š๐ซ๐ญ๐ฌ ๐–๐ข๐ญ๐ก ๐‚๐ฅ๐ž๐š๐ซ ๐๐š๐ฆ๐ž๐ฌ In software, names are everywhere: Variables, Functions, Classes, Files & folders, etc. Good names make code readable. Bad names waste time. Inspired by "๐˜Š๐˜ญ๐˜ฆ๐˜ข๐˜ฏ ๐˜Š๐˜ฐ๐˜ฅ๐˜ฆ ๐˜ฃ๐˜บ ๐˜™๐˜ฐ๐˜ฃ๐˜ฆ๐˜ณ๐˜ต ๐˜Š. ๐˜”๐˜ข๐˜ณ๐˜ต๐˜ช๐˜ฏ", here's a quick summary of naming rules every developer should know.

How to Name Your Code: A Guide to Meaningful Naming

Use Intention-Revealing Names

Make the code easier to understand by using clear, descriptive names for variables, functions and constants.

When names describe their purpose or role in the code, it become easier for other (or even for yourself) to understand what the code does without having to guess or remember hidden details. This helps make the code more maintainable and easier to change later.


Avoid Disinformation

  • Avoid using names that mean something else like hp to mean hypotenuse its confusing why? because hp is also a name for some unix system, better to use โ€hypotenuseโ€ or โ€hypโ€,
  • Avoid using the wrong type name, donโ€™t call something โ€accountListโ€ if it is not a list because list has a special meaning for programmers, better to use โ€accountGroupโ€ or โ€bunchOfAccountโ€ or just โ€accountsโ€ would be better.
  • Beware of using names that are too similar for example โ€XYZControllerForEfficientHandlingOfStringsโ€ and โ€XYZControllerForEfficientStorageOfStringsโ€, these names look the same. Itโ€™s hard to see the difference, better to make names more different, so they easier to understand.
  • Avoid Using letters look like numbers, like l small โ€Lโ€ looks like 1, o (big โ€Oโ€) looks like 0.

Make Meaningful Distinctions

Donโ€™t just change variable names to make the compiler happy. Make your names meaningful, if you have to make names different, make sure the difference actually matters and say something.

  • Number-series names: Names like a1, a2, a3 etc, are not wrong to the compiler but they are useless to humans. They donโ€™t tell us anything about whatโ€™s going on.
  • Noise words: Words like Info, Data, Object, Variables etc, these donโ€™t add any real meaning.
  • Similar names: The variable moneyAmount is indistinguishable from money, customerInfo is indistinguishable from customer, and accountData is indistinguishable from account. Distinguish names in such a way that the reader knows what the differences offer.

Use Pronounceable Names

Humans are good at words. A significant part of our brains is dedicated to the concept of words. and words are by definition pronounceable. It would be a shame not take advantage of that huge portion of our brains that has evolved to deal with spoken language, So make your names pronounceable.

Some developers write names like this:

These names are hard to say and hard to understand. You canโ€™t talk to your team and say โ€Check genymdhms or pszqintโ€ that sounds weird.

By the way "genymdhms" stands for generation date, year, month, day, hour, minute and second, but itโ€™s hard to figure out what it mean.

Use names that are easy to say instead of "genymdhms" use "generationTimestamp", now you can say โ€Hey look at the generationTimestamp itโ€™s wrongโ€.
โ€œEasy to talk about. Easy to understandโ€

Use Searchable Names

Single-letter and numeric constants have a particular problem in that they are not easy to locate across a body of text.

  • Numeric constants: For example if you have a constant like MAX_CLASSES_PER_STUDENT, it is easy to search for it in your code, but if you just write the number 7 in many places, it is hard to find where you used that number.
  • Single-letter: The same problem with single-letter names like โ€œsโ€ or โ€œeโ€, the letter โ€œeโ€ is very common in english and in code, so it is hard to find the right โ€œeโ€ you want.
  • Preference: the length of the name should match its scope, small scope => short names, large scope => longer, descriptive names.

Avoid Encoding

Encoding means adding extra information in the code, like the type or scope, for example writing strName to say this is a string or iCount to say it is an integer, it makes names hard to read because you need to learn the rules of the encoding.

New people who join a project must learn this extra code, which is confusing.

Interfaces and Implementation

When using interfaces and classes, some people write names like :

  • Interface: IShapeFactory 
  • Class: ShapeFactory

Putting โ€Iโ€ before the interfaces itโ€™s old style and not helpful, So if we need to encode either the interface or implementation we choose the implementation

  • Interface: ShapeFactory
  • Class: ShapeFactoryImpl

Avoid Mental Mapping

Donโ€™t make readers guess or translate your variable names in their head.

The names should be clear and easy to understand. Sometimes people using single letters like i, j or k for loop counters, this is ok because itโ€™s very common and easy to understand in small loops. But in other cases using one letter like c is bad, because the reader have to remember or guess what c stands for.

Smart programmers sometimes like to use short or tricky names to show they are clever.

But professional understands that Clarity is king, they write code that others can understand easily.

Class Names

A class represents something, like a thing or a concept. So class names should be nouns or noun phrases like Customer, WikiPage, Account, AddressParser, etc.

Avoid generic or unclear words like Manager, Processor, Data or Info these donโ€™t clearly tell what the class really does or represents.

Method Names

A method performs an action, so it should be a verb or verb phrase like postPayment(), deletePage() or saveProduct().

If itโ€™s a getter, setter, use JavaBean-style getName(), setName(โ€Mikeโ€), If you're using ES6 get and set keywords, skip the prefix.

If itโ€™s a Booleans should start with: is, has, can, should, was, hasPermission(), canEdit(), isLoading().

Donโ€™t Be Cute

These are slang or jokes from a cartoon or a movie, you might think itโ€™s funny, but other developers may not understand it and you may forget what it means after some time, itโ€™s not clear what the function really does.

These names say what the function does simple and clear.

Pick One Word per Concept

If you pick one word to mean something, use it everywhere, donโ€™t change it.

user.fetch(), product.retrieves(), order.get(), all of them do the same thing (get data), but you used three different words, and thatโ€™s confusing, letโ€™s pick one word like get() and use it everywhere: user.get(), product.get(), order.get(), now itโ€™s clear and easy.

Another example, letโ€™s say you name your classes like this: DeviceManager, ProtocolController, USBDriver, whatโ€™s the difference between a โ€Managerโ€, โ€Controllerโ€ and a โ€Driverโ€, maybe they do the same thing! But the names are different, so we get confused. You should pick one word maybe โ€managerโ€ and use it for all DeviceManager, ProtocolManager and USBManager now your code is consistent.

Donโ€™t Pun

Avoid using the same word for different concept, letโ€™s imagine that we use the name โ€addโ€:

  • order.add(item): which puts an item in the list
  • calculator.add(a, b): which does a + b

Same word different meaning. Thatโ€™s a pun, it look the same, but itโ€™s not really the same action.

Use different names for different ideas

  • order.insert(item)
  • calculator.add(a, b)

now itโ€™s clear. No pun. No confusion.

Use Solution Domain

When youโ€™re naming your code use the power of technical terms that other developers can understand.

JobQueue this is clear to any developer, itโ€™s a queue of jobs/tasks.

Using names like this save time because other developers donโ€™t need to guess or ask what it does.

Use Problem Domain Names

When you write code that reflect real world-business logic, use names from the business domain, for example if youโ€™re building a system for car garage use names like:

  • Invoice
  • Mechanic
  • CustomerVehicle

Add Meaningful Context

Sometimes variable or function names donโ€™t mean much on their own. You need to give them context by enclosing them in well-named classes, functions or namespaces when all else fails then prefixing the name may be necessary as a last resort. instead of just a state, write addrState this tells us itโ€™s a related to an address not a game or app state.

These variables are used to build a message like โ€These are 5 guessesโ€, but the names have no meaning on their own.

Now itโ€™s obvious these are part of a guess statistics message.

Donโ€™t Add Gratuitous Context

When naming classes, modules or functions, avoid adding unnecessary prefixes that repeat the applicationโ€™s name or domain.

Imagine you app is called โ€Gas Station Deluxeโ€, it is bad idea to prefix every class with GSD. Example:

It's not helpful because when you type 'G' and use autocomplete, you get a long list of classes. Use shorter names when possible, but always make them clear and provide meaningful context.

Final Word

  1. Picking good names is hard it need good thinking and a shared cultural background.
  2. Many people donโ€™t learn naming well because itโ€™s not a technical or business skill itโ€™s a teaching issue.
  3. Use refactoring tools to rename.
  4. Clear naming helps in the short term and the long term.

On This Page

    Share this article

    FacebookX (Twitter)LinkedInWhatsApp

    Keep Reading

    Letโ€™s Build the Future Together

    Iโ€™m always ready for new challenges and exciting projects. Whether you have an idea or need expert guidance, let's collaborate and turn your vision into reality. Reach out, and letโ€™s make something extraordinary!

    linkedinfacebookgithubtwitter

    Y.ALOUANI

    // Bad Code
    x = 5;
    y = 10;
    z = x * y;
    // Good Code
    width = 5;
    height = 10;
    area = width * height;
    // Bad Code
    function copyArray(a1, a2) {
      for (let i = 0; i < a1.length; i++) {
        a2[i] = a1[i];
      }
    }
    // Good Code
    function copyArray(source, destination) {
      for (let i = 0; i < source.length; i++) {
        destination[i] = source[i];
      }
    }
    // Bad Code
    let moneyAmount = 10000;
    let money = 15000;
    
    // Good Code
    let totalPrice = 10000;
    let userBalance = 15000;
    let genymdhms;
    let pszqint;
    // Bad Code
    
    for (let j = 0; j < 34; j++) {
      s += (t[j]*4)/5;
    }
    
    // Good Code
    const WORK DAYS PER WEEK = 5;
    const NUMBER OF TASKS = 34;
    let realDaysPerIdealDay = 4;
    let sum = 0;
    for (int j = 0; j < NUMBER OF TASKS; j++) {
      let realTaskDays = taskEstimate[j] * realDaysPerIdealDay;
      let realTaskWeeks = realTaskDays / WORK DAYS PER WEEK;
      sum += realTaskWeeks;
    }
    // Bad Code
    eatMyShort();
    whack();
    holyHandGrenade();
    // Good Code
    abort();
    shutDown();
    deleteItems();
    // Bad Code
    let number;
    let verb;
    let pluralModifier;
    // Good Code
    class GuessStatisticsMessage {
      number;
      verb;
      pluralModifier;
    }
    // Bad Code
    class GSDAccountAddress {}
    class GSDUserProfile {}
    The Ultimate Guide to JavaScript: Mastering the Web's Most Popular Language

    The Ultimate Guide to JavaScript: Mastering the Web's Most Popular Language

    2025-01-20
    Javascript|language|databases

    JavaScript is the lifeblood of the modern web. From simple interactive buttons to full-fledged web applications, JavaScript powers it all. Whether you're a beginner or an experienced developer, there's always something new to learn about this versatile language. In this blog, we'll explore JavaScript's origins, its core features, and why it remains the cornerstone of web development.

    React: Building Dynamic User Interfaces with Ease

    React: Building Dynamic User Interfaces with Ease

    2025-01-18
    Web Development|JavaScript|React|language

    React is a powerful library for creating dynamic and efficient user interfaces. Learn how it simplifies development with reusable components, state management, and a vibrant ecosystem.