DEV Community

Hector Williams
Hector Williams

Posted on

Clean Coding Guidelines Every Developer Should Know

Introduction
Software is a critical part of the modern world and it needs people to design, develop, test and maintain it. Due to the nature of life, there are often turnovers on a company's payroll. Employees retire, die or leave their role for other reasons. This presents the company with a challenge-how to create code that can be maintained and upgraded by other software engineers. Due to this, clean coding guidelines have been invented. The term was popularized by Robert C.Martin aka "Uncle Bob" and explained in his book. Clean Code These guidelines ensure that code is easy to read, easy to maintain and easy to change. They are as follows.

1.Meaningful Naming
Descriptive names should be used for variables, methods and classes that reflect their purpose and behavior. Single letter names should usually be avoided. This makes the code easier to read and understand and the logic easier to follow. It can also help in debugging the code.

Bad Example:

int d; // days since creation

Enter fullscreen mode Exit fullscreen mode

Good Example:

int daysSinceCreation;

Enter fullscreen mode Exit fullscreen mode

2. Small, Focused Functions

As an application of the Single Responsibility Principle, functions and methods should be designed so that they carry out one goal. They should also be small. This way functions will be easier to read ,reuse, test and maintain.

Bad Example:

void processOrder(Order order) {
   // validate order
   // calculate totals
   // apply discounts
   // update inventory
   // notify user
}

Enter fullscreen mode Exit fullscreen mode

Good Example:

public class Example {
    public void doWork() {
        System.out.println("Working");
    }
}

Enter fullscreen mode Exit fullscreen mode

3. Consistent Formatting
Formatting should be consistent. Spacing should be minimal in both the horizontal and vertical directions and the code should appear neat. Font sizes should be consistent. Following these rules should make the code easy to read.

Bad Example:

public class Example{
public void doWork( ){System.out.println("Working");}}

Enter fullscreen mode Exit fullscreen mode

Good Example:

public class Example {
    public void doWork() {
        System.out.println("Working");
    }
}

Enter fullscreen mode Exit fullscreen mode

4. Comment wisely
Comments are unnecessary if the code is well written. Good code will be self expressive. Don’t state the obvious. Use comments to explain “why” something is done, not “what.” If code is too confusing and you feel the need to over-comment, it’s usually a sign the code itself needs refactoring.

Bad Example:

i++; // increment i by 1

Enter fullscreen mode Exit fullscreen mode

Good Example:

// Retry up to 3 times because the external API is unreliable
retryOperation();

Enter fullscreen mode Exit fullscreen mode

5. Avoid Duplication
Duplicated code will lead to copies of the same code snippets all over the code base. Whenever a change needs to be made, the changes need to be made in a number of places. Otherwise, the code will break. Changes will also be time consuming. Hence, we need to centralize the code in order to make maintenance easier.

Bad Example:

if (userType.equals("Admin")) { /* logic */ }
if (userType.equals("Manager")) { /* same logic */ }

Enter fullscreen mode Exit fullscreen mode

Good Example:

if (isPrivilegedUser(userType)) {
   // logic
}

Enter fullscreen mode Exit fullscreen mode

6. Error Handling
As with life, the unexpected happens during software execution and we thus need to design and implement code in such a way to handle errors. Handling of the errors should also produce the correct error messages in order to debug the system. Proper error handling ensures failures are visible and recoverable, making systems more robust.

Bad Example:

try {
   doSomething();
} catch (Exception e) {
   // ignore
}
Enter fullscreen mode Exit fullscreen mode

Good Example:

try {
   doSomething();
} catch (IOException e) {
   log.error("File operation failed", e);
   throw e; // or handle gracefully
}

Enter fullscreen mode Exit fullscreen mode

7. KISS (Keep it Simple Stupid)
Write code that is code that’s easy to read, understand, and maintain. Avoid clever tricks or overly complex logic that only the original author can follow. Simpler code reduces bugs, makes future changes easier,helps onboards new members faster and encourages modularity.

Bad Example:

if ((user.isActive() && user.hasSubscription()) || 
    (user.isAdmin() && !user.hasSubscription() && config.isEnabled())) {
    allowAccess();
}//Hard to read,easy to make mistakes later.

Enter fullscreen mode Exit fullscreen mode

Good Example:

if (canAccess(user)) {
    allowAccess();
}

private boolean canAccess(User user) {
    return (user.isActive() && user.hasSubscription()) || user.isAdmin();
}//The logic is isolated; The main flow is readable at a glance and easier to test and maintain.

Enter fullscreen mode Exit fullscreen mode

8.Follow SOLID Principles

https://dev.to/hectorw_tt/the-solid-principles-of-object-oriented-programming-4bff

9.Write Tests
Tests are your safety net. Unit tests confirm small pieces work correctly, while integration tests check the bigger picture-how well multiple components work together. Writing tests ensures that your code does what it should do. Without tests, “clean” code can still hide regressions and future breakages. Clean code is testable code.

Example
Suppose you have a method that calculates the area of a rectangle:

public int area(int width, int height) {
    return width * height;
}

Enter fullscreen mode Exit fullscreen mode

Unit Test


@Test
public void testArea() {
    Rectangle rect = new Rectangle();
    assertEquals(20, rect.area(4, 5));
    assertEquals(0, rect.area(0, 5));
}

Enter fullscreen mode Exit fullscreen mode

10.Refactor Regularly
Refactoring means improving the structure of your code without changing its behavior. It’s like cleaning up a messy room: you don’t throw anything away, you just organize it so it’s easier to use.

Example:
Before refactoring:

void processOrders(List<Order> orders) {
    for (Order o : orders) {
        if (o.isValid() && !o.isShipped()) {
            double total = 0;
            for (Item i : o.getItems()) {
                total += i.getPrice() * i.getQuantity();
            }
            if (total > 1000) {
                // apply discount
            }
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

After refactoring:

void processOrders(List<Order> orders) {
    for (Order order : orders) {
        if (canProcess(order)) {
            applyDiscountIfNeeded(order);
        }
    }
}

private boolean canProcess(Order order) {
    return order.isValid() && !order.isShipped();
}

private void applyDiscountIfNeeded(Order order) {
    double total = calculateTotal(order);
    if (total > 1000) {
        applyDiscount(order);
    }
}

private double calculateTotal(Order order) {
    return order.getItems().stream()
                .mapToDouble(i -> i.getPrice() * i.getQuantity())
                .sum();
}

Enter fullscreen mode Exit fullscreen mode

Conclusion
In the ever-evolving field of software development, writing clean code is paramount. It ensures that codebases are maintainable, scalable, and understandable, facilitating easier collaboration and long-term project success. In conclusion, following these habits will lead to code that is easy to read, maintain and update even when the team that is working with this codebase changes on a regular basis.What are your clean coding recommendations?

Additional Resources: Clean Code by Robert C.Martin

Top comments (0)