Writing a Clean Code And Why It Matters

Pritesh Bhate
Globant
Published in
7 min readOct 11, 2022

I often encounter questions like “what exactly clean coding is all about?”, Is it just about using proper indentation, commenting & code refactoring?

Well, it’s certainly a lot more than that. So, guys, in this article we are going to discuss what is exactly clean code & why is it so important in the industry.

Let’s first start with what is clean code.

Clean code is all about writing code that is easy to read, understand and change. A straightforward code reduces the need for speculation and the potential for misunderstandings, regardless of whether the reader is the code’s original author or someone else.
Code should follow these key principles: KISS, which stands for Keep It Simple, Stupid, and DRY, Don’t Repeat Yourself. Ask yourself if there is a better solution for solving problems or complexity within your code.
Let’s dissect and elaborate on factors that are conducive to clean code, such as:
1. Follow Proper Naming rules

While naming a variable, function or class always keep in mind its purpose and use descriptive and unambiguous names. For example:

Dirty:
List<Integer> p = new ArrayList<Integer>() ;
Clean:
List<Integer> prices = new ArrayList<Integer>() ;
Dirty:
for (let i = 0; i <= 10; i++) {
// do some thing
}

Clean:
const totalEmployees = 10;
for (let i = 0; i <= totalEmployees; i++) {
// do some thing
}

When writing your classes, name your classes with the following guidelines:

  • Classes should be Nouns, Clean: User, Account, Product
  • Avoid Generic Classes that can become a magnet where lazy developers can come and write on them, so be specific.
    Dirty: Utility, Common
    Clean: PaymentsUtility

Naming Methods Should Clearly Express Intent :
The method name should say it all, and it is mostly a verb, it should clearly express your intent.

Dirty:
send();
insert();
Clean:
sendEmail();
insertRegisteredEmployees();

2. Function rules

  • Always try to make it small. Don’t make it a monolith. If you can break it into separate reusable chunks you should always do it.
  • Make function arguments as few as possible.
Dirty:
searchEmployee(String name, int age, int empId, String companyName, String position, String address);
Clean:
searchEmployee(int empId);
  • Make your function in a way that it always returns a consistent type. Your function should not return different data types in any case.

3. Avoid Abbreviations

you need to avoid abbreviations because it creates ambiguity, and it makes your intent not clear and subjected to misinterpretation.

Dirty:
regEmp();
calP();
Clean:
registerEmployee();
calculateFinalPrice();

4. Use lint checks

Most of the popular programming languages have lint checkers available in the popular IDE they use. You can also configure lint on your specific projects. These lints help to avoid some minor mistakes like variable, class, method naming, code duplicates, indentation error, etc. beforehand. Be sure to set up the project in a way that when you push your code to the GitHub repo it always checks if there are any lint errors in your code.

5. Write code comments

This is one of the essential virtue a programmer should have. Always try to comment on your codes explaining the intent of your code. You should avoid commenting out the code and leaving it. It’s better to just remove it. Since nowadays everybody uses git, you can easily view history and revert your code if you need it again. You should not add an unnecessary comment that doesn’t serve any purpose. Don’t make your comment redundant and obviously don’t be a person like below.

6. Follow coding pattern

DRY: DRY stands for “Don’t Repeat Yourself”. As the name states, it discourages the repetition of code. If we repeat code in our projects if anything changes we will have to make changes in all places.

KISS: KISS stands for “Keep It Simple, Stupid”. If your code is simple to understand then it is easy to maintain as well. After all programming language is to be understood by us humans more because computers can understand only 0 and 1. Don’t bring unnecessary complexity to your codes. Never write a code that will leave you scratching your head when you check it after a month.

YAGNI: YAGNI stands for “You Aren’t Gonna Need It”. Sometimes we developer tends to think ahead of thing and write code extra features thinking we may need them in the future. You should always focus on your existing feature rather than worrying about some imaginary complex feature that may or may not be needed and could be removed or changed.

SOLID Design Principles: These are five principles of Object-Oriented class design. They are a set of rules and best practices to follow while designing a class structure.
Following the SOLID acronym, they are:

  • The Single Responsibility Principle
  • The Open-Closed Principle
  • The Liskov Substitution Principle
  • The Interface Segregation Principle
  • The Dependency Inversion Principle

7. Compare Booleans Implicitly and not Explicitly

It's better to compare your booleans implicitly, be DRY, lets's take these two examples:

Dirty explicit comparison:

if (employeeRegistered == true ) {// do something }

Clean implicit comparison:

if (employeeRegistered) {// do something }

The implicit comparison is less code, and more intuitive in the sense that when you read it or when other developers read it.

Assign Booleans Implicitly as well :
Dirty:

boolean goingToSchool ;if ( totalStudents > 20 ) {
goingToSchool = true;
} else {
goingToSchool = false;
}

Clean:

boolean goingToSchool = totalStudents > 20;

Now, this reads like a speech “I will go to school if the count of total students is greater than 20“ and has fewer lines, also you don’t have a separate line for initialization.

8. Avoid Magic Numbers!

As we mentioned before, its really important to understand the programmer’s original intent, when you have magic numbers that you only understand it will be difficult for other developers to know your intent take this as an example:

Dirty:

if (age >= 18) {// do something }

18 is a magic number and you might have guessed it, but we don’t want you to guess it, we want you to be sure that this is the intent, here is a better implementation:

Clean:

int VOTING_AGE = 18;
if (age >= VOTING_AGE ) {
// do something }

9. Error Handling

Error handling is a vital part of programming. You should never be lazy to handle errors. If you have implemented proper error handling, your code will continue to function without crashing. An unhandled error can cause your program to crash, end-user to lose their work, and if it supports stack trace error it can even release some vital information related to your projects or servers.

10. Practice Test Driven Development (TDD)

Test Driven Development is an agile practice that requires the programmer to write an initially failing automated test case that defines a desired improvement or function. This software development process requires a very short yet repetitive development cycle that produces the minimum amount of code to pass that test. Finally, it allows the developer to refactor the new code to acceptable standards.

To apply TDD, the following steps are generally followed:

  • Add a test
  • Run all tests and see if the new one fails
  • Write some code
  • Run tests
  • Refactor code
  • Repeat

Besides these above steps, you can also further improve your code quality by self-reviewing your own code by making sure you follow the above points. Always revisit your code and check if you can optimize it furthermore. Ask your other team members to review your codes and as feedback from them. Since you will never want to get hurtful comments from others be sure to give positive feedback to your teammates when you’re reviewing their codes. Rather than going line by line to check minor errors be sure to use lint checkers to automate those processes.

WHY IS IT IMPORTANT?

One fact which is undeniable in the Software Industry (regardless of which programming language, platform & framework you are using) is “Change”.

If a small change request or a minor functionality addition in the system causes a partial or complete restructuring of the existing code, then that code cannot be considered “Clean”.

Frequent modifications to an existing block of code by different people eventually violate the general Clean Coding principles and ultimately force you to rewrite the entire code with a new design.
For example, frequent modifications often result in code redundancy, old misleading comments which are not updated after subsequent modifications and lengthy functions which could have been easily broken into multiple logical blocks.

In essence, a code must adhere to the basic design principles along with the other general Clean Coding principles in order to sustain future changes in the business requirements.

What are the benefits of the Clean Code?

  • Create easily maintainable & extensible code
  • Easy to debug & refactor
  • Eventually, you will write unbreakable code
  • Writing clean code might cost you time in the first place, but you will end up spending less time on maintenance
  • Others will understand this more easily.
  • It will be easier to test.
  • It will be easier to protect.
Clean code always looks like it was written by someone who cares. There is nothing obvious you can do to make it better. - Michael Feathers

--

--