Clean Code

What Is Clean Code?

When we talk about clean code, we talk about a reader-focused development style that produces software that’s easy to write, read, and maintain. Clean code is code that is easy to understand and easy to change.

  • Clearness

  • Best Practices

  • Maintenance

  • Easy to Test

  • Simplicity

  • Consistency

Optimisation vs. Readability

Always write code that is simple to read and which will be understandable for developers. Because time and resources that will be spent on hard readable code will be much higher than what you get from optimisation.

Structure your code such that its readable then it requires less comment s.

Reading your code should be pleasant

Avoid Obvious Comments

More comments means more to keep up to date

// get the country code
String countryCode = getCountryCode();

// if country code is US
if (countryCode == 'US') {

    // return coutry code
    return countryCode;
}

Consistent indentation

Code should have an indentation of 4 characters

function myMethod() {

    if(true){
    
        doSomething();
        
    } else {
        doSomethingElse();
    }
}

Code Grouping & Code Spacing

Often the code in your methods can be arrange into a series of actions:

  1. Get data

  2. Filter data

  3. Manipulate data

  4. Return data

Adding a comment at the beginning of each block of code also emphasise the visual separation.

// get geo data
GeoData data = GeoDataAccess.get(recordId);

// create request
GoogleMapsRequest request = GoogleMapsFactory.createRequest(data);

// query google maps
GoogleMapsResponse response = GoogleApi.search(request);

// validate response
ValidateResponse(response); 

return response;

Avoid Deep Nesting

Too many levels of nesting can make code harder to read and follow. Change your code to reduce the level of nesting.

// bad 

function Boolean eampleMethod(Id recordId) {
 
    if (isAccessable(recordId)) {
 
        if (idValid(recordId)) {
 
            if (isEmpty(recordId)) {
 
                if (canUpdate(recordId)) {
 
                    // do something
 
                } else {
                    return false;
                }
            } else {
                return false;
            }
        } else {
            return false;
        }
    } else {
        return false;
    }
}

Pick One Word per Concept

Pick one word for one abstract concept and stick with it.

For instance, it’s confusing to have fetch, retrieve, and get as equivalent methods of different classes.

Variables

Naming

Use Camel Case: First letter of each word is capitalised, except the first word.

Integer numOfRecords = 10;

Length

Avoid shorten variable names

// bad 

OpportunityListItem oli;
Id acId;

// good

OpportunityListItem lineItem;
Id accountId;

Arrays or Lists

Pluralisation of the variable name makes sense or appending List

// bad

List<Account> accs;
List<Account> account;
List<Account> data // too generic
List<Account> list; // no context

// good

List<Account> accounts;
List<Account> activeAccounts;
List<Account> accountList;

Boolean

Boolean's can hold only 2 values, true or false. Given this, using prefixes like is, has, and can will help the reader infer the type of the variable.

// bad
Boolean open = true;
Boolean write = true;
Boolean fruit = true;

// good
Boolean isOpen = true;
Boolean canWrite = true;
Boolean hasFruit = true;

Numbers

For numbers, think about words that describe numbers.

Prefix words like max, min, numOf or total

// bad
Integer accounts = 3;

// good
Integer minAccounts = 1;
Integer maxAccounts = 5;
Integer numOfAccounts = 5;
Integer totalAccounts = 3;

Constants

Use upper case with under scores:

final Decimal TAX_RATE = 0.2;

Use pronounceable names and searchable names

When a name is pronounceable mostly it is searchable and searchable names is a must to enhance find operations in refactoring. Avoid using a single letter named variable.

// bad 

Date d;
Time t;
DateTime dt;

// good

Date birthday;

Function names should be verbs

Last updated