Best Practices

How to Name Classes, Functions, and Variables

Naming variables play a huge role in making code more human readable. This only improves on the overall quality of the code and make it better maintainable.

General rules

It's important to keep in mind the following prior to naming a variable, method, and/or class.

Should

  • Be specific
  • Have single responsibility

Avoid

  • Generic suffixes that add no value
  • Abbreviations that add any ambiguous meaning

How to Name a Variable

When naming a variable it's important to be specific to what the variable reflects.

Should

float total = 0;
array employees = ["John", "Marry"];

Avoid

float t = 0;
array e = ["John", "Marry"];

How to Name a Method

Name a method to be a verb/action. The method name should be sufficient enough to describe to the reader the exact functionality. You may ask, how do you do this as functions can be complex; this may be a good indicator that the function need to be split into two or more sub functions. A function should do exactly one task.

Should

functiong validateUser()
{
    // This function should purely validate the user's information.
    // It should not do any saving at all.
}

function registerUser()
{
    // This function should not have any logic to validate the user's information.
    // Otherwise it creates unexpected side effects and makes people read every single line of code to find out if it does anything else than its title.
}

Avoid

function validate()
{
}

function regUsr()
{
}

How to Name a Class

The class name should be a noun. It should reflect what the class is responsible for without making the reader need to read the header or whole code to figure it out. Avoid giving classes generic names. Doing so, will make these classes on what we call magnet classes; classes that attract lazy developers to add generic functions there.

Should

class StripePaymentUrlQueryBuilder()
{
}

class StripePaymentProcessor()
{
}

Avoid

class Utility()
{
    // Magnet class
}

class Processor()
{
    // Magnet class
}

How to Name a Boolean

Let's be positive. This is what you need to think of when naming a boolean. Always name the variable in a way where true represents a positive indicator. It's also important to be specific on what exactly the variable portray.

Should

boolean isUserActive;
boolean userLoggedIn;

Avoid

boolean status;
boolean login;
boolean isUserNotActive;
boolean userNotLoggedIn;
Author image

About Rawad Hilal

Lead programmer with a track record of incorporating user and business requirements into cost-effective, secure and user-friendly solutions known for scalability and durability.
  • Orange County, California, USA