Niraj Chauhan

Niraj Chauhan

#father #husband #SoftwareCraftsman #foodie #gamer #OnePiece #naruto

How to write clean code?

Posted by on

A project is much easier to develop and maintain if the codebase is clean, which every developer should strive for. Writing clean code is not rocket science, in fact, it’s quite simple.

1. First & foremost you need Focus

When a developer starts to code, the focus is an absolute must. You can’t be doing other things in parallel and achieve clean codebase. While coding, a developer is required to do a lot of things apart from just writing the code e.g. ALT+TAB to switch between terminal, browser and code editor, change tabs within the editor, refer or understand the dependent code etc.. this could be time-consuming and if your mind is not focused then you will end up in writing bad code.

2. KISS

I have usually noticed people over-complicating their code by thinking of extreme future scenarios, one should simply avoid these. For instance, the following code for Summing two numbers.

class Calculator{
    private int a;
    private int b;
    private String operator;

    Calculator(int a, int b, String operator) {
        this.a = a;
        this.b = b;
        this.operator = operator;
    }

    int getCalculatedValue(){
        switch (operator){
            case "+":
                return a + b;
            default :
                return 0;
        }
    }
}

While there is nothing wrong with the code, It’s been extended to function as a calculator in future, which may or may not be required. Summing up two numbers can simply be a one-liner code.

The example in itself is not very realistic, but the point here is to not make things overcomplicated, Keep it Simple Silly (KISS) !! It’s good to design but focus on a simplistic approach to the problem at hand. Follow KISS principle.

3. Naming Conventions

The name of a variable, method or class is very important in your code, it makes a lot of difference while interpreting the logic.

For example: Creating a variable for elapsed time in days:

DateTime d

Now if someone reads this, it looks like some DateTime type variable. But now if I modify it to something like this:

DateTime elapsedTimeInDay
// or
DateTime daysSinceCreation;

This makes a significant difference. So think of a good meaningful name and then write the code.

4. Feedback

Get your code reviewed by someone from time to time. Even if you follow above practices, it’s impossible to say that the written code will be clean. By getting your code reviewed, you get feedbacks and feedbacks are always good for improvements.

5. Pairing

Code review helps but it can be time-consuming. Let’s say a developer takes an hour to write some code, he then gets it reviewed by some other developer and start making changes based on feedback, which takes another 30-40 mins. This is time-consuming. What if from start the reviewer was sitting next to the developer, then the moment developer started writing the first line of code, it gets reviewed simultaneously. So in an hours time, the developer has a clean reviewed code. Pairing is a nice practice to follow. The way pairing works, developer A & B pairs together for an hour. First 30 mins A codes and B reviews, and in next 30 mins B codes and A reviews. The end result is good quality & clean code.

6. TDD

In general regressions for refactoring happens a lot of time. But after refactoring how can one make sure that the functionality is still the same? Test driven development approach ensures that refactoring your code will never negatively impact the desired functionality. The way TDD works is, you write test-cases first, run it, see it fail, then you write code and make the test-cases pass, repeat this and keep refactoring whenever you feel like. Now while refactoring you don’t need to worry about missing any functionalities because your test cases will help you. In a way, it’s kind of an alert mechanism which notifies you when your refactoring has gone wrong.

7. Boy Scout Rule

Follow Boy Scout Rule, which means always leave the code cleaner than you found it. This forces the developer to continuously keep improving the project’s code quality by refactoring it and making it simpler.

8. DRY

Don’t Repeat Yourself, basically always write new code, don’t repeat the same code again and again. Try to extract generic behavior in some method and reuse that in other methods.

Conclusion

According to me, a codebase is clean only when it’s readable and maintainable. If you follow from point 1 to 5, you will achieve readability, and if you follow from point 6 to 8, you will achieve maintainability. Now combine all of them you achieve clean codebase. Let me know what you think of clean coding practices and if I have missed anything, in the comment section below.