Skip to main content
Image
Untitled%20design%20%2818%29_0.jpg

The Art of Clean Code

article publisher

Gurpreet Kaur

Technology

Our ability to speak and communicate ourselves to others in a way that they understand every nuance of our feelings and thoughts makes humans far more superior than any other species. This is attributed to our language. Even the people who cannot speak and hear have developed a sign language that has made it possible for them to communicate. 

Can you imagine living without it? 

I cannot. The world won’t be the same without language and communication. 

Now taking this conversation towards web development, which has a language of its own and that is coding. Developers write code, which is the only way they are able to communicate their ideas, thoughts and plans to the computer and build the wonderful programs and applications that they do. A computer would be able to understand the code, despite it being clear or not. However, when a human is able to read, understand and evaluate its logic, that is when you can call yourself an expert of the language. 

At present, writing code is not that complicated a task. Anyone can do it. There are books and tutorials available that claim, quite emphatically, that they can teach you how to code in just two weeks and then you can build any application that you want. Isn’t that great?

If I were to tell you that I planned to learn Mandarin on the 1st of January and by 14th, I was able to speak fluently and I got an interpreter’s job, would you believe me? I can already sense the skepticism. 

The same is true for coding, you can’t learn it efficiently enough to become a master at it in a few weeks. Like any other language, it is an art and it needs time, focus and dedication to master. 

So, today I have taken it upon myself to tell you all about coding in the clean way. Because anyone can code, but not many can write a clean code, that other developers are able to understand through a slight glance. That is the epitome of coding and that is what you should be trying to achieve.

What is clean code?

I wasn’t very subtle in the introduction, so you might have guessed what a clean code is. Still I want to elaborate on it a little more. 

Clean code has two words making it whole. You guys probably know the A to Z of coding, so I won’t get into that. It’s the term clean that needs an explanation and I will use an analogy for that. Okay, so all of us like to keep our homes clean, but all of us do not do it in the same way. We have developed different techniques and methods to achieve the cleanliness we aim for. The end result would always be a pristinely clean home, where everything is in order and you can easily find anything you are looking for. 

A clean code is something similar to that, well, a lot similar if you ask me. In essence, a clean code is one that is simple, so that it becomes easily understandable, changeable and testable with its scope isolated. 

Let me explain the two main features of a clean code in a little detail; 

Easy to understand 

When I said clean code is easily understood, I mean it is easy to read, with every word painting a clear picture in the mind of the reader. Understanding the code also means that its execution flow is clear, its object collaboration is concise, its classes have precise roles and responsibilities and its variables and expressions have a purpose.

Easy to change

When I said it is easily changeable, I meant that extending and refactoring the code is simple and fixing bugs is a piece of cake. I would be wrong to say that this is an entirely different point, because when changes are introduced in a code, the developers have to be certain that they do not break the existing functionality. This only happens when he absolutely and completely gets an 360° understanding of the code. Consequently, the code becomes easy to test as well.

If I had to sum up a clean code, I would say it is everything from being organised to being full-proof. 

The difference between clean code and unclean code is explained in a diagram.
Source: X-Team 

The above picture very concisely and humorously sums up the difference between a good/clean code and a bad/dirty code. There are going to be WTF moments, but there number is what differentiates the two.

Knowing the dirty 

A dirty code is exactly that, it is unclean, unorganised, messy and everything else a clean code isn’t. If there is no logic, no system and minimal understanding of the code, then you, my friend, have ended up with a pretty dirty code. 

Imagine yourself in a situation where you have to find your favourite shirt in a closet that hasn’t been organised in over a year. I am not sure you will be able to find it.  Even if you could, it would take a long time to find it and you would end up with a much greater mess than you already had.

So, a dirty code, which is really hard to understand will slow you down and take a lot more effort from your end to perform even the simplest of tasks. Bugs fixes will give you a headache, that’s for sure. It would hamper your efficiency, the success rate of your projects would plummet and your developers and you would abhor what you would end up with. 

With such a pretty picture in mind, I am sure you would be itching to know how to clean up your code or start building a clean one from scratch. Don’t worry, I have the answer for you. 

What are the principles of a clean code?

Coding in the clean way isn’t all that complicated, it isn’t something that is impossible to achieve. You just have to follow a few principles to the T, without any deviation or cutbacks and you will never find yourself with a dirty code. Since I am pretty sure you want that, read and implement, my friend.

The principles of clean code are written in eight circles.


Follow the simple path: KISS

The acronym KISS stands for Keep It Simple, Stupid. Surprisingly, this term came from the US navy back in the 60s. Like the name says, this principle insists on keeping things simple. You should not have to complicate things by adding a piece of complex code, when a simple one line code could effectively do the job. 

Keep things simple. Keep them understandable. Keep them concise, so that even 10 months down the line, you are able to understand what you did now. Being too clever isn’t always a great thing.

Eliminate the repetitions: DRY

DRY refers to Don’t Repeat Yourself because if you do, you're going to end up with a dirty code. This principle clearly states to avoid duplication of data and logic. And provides an alternative for the same and that is finding logic in repetitions. 

You could duplicate lines or you could find an algorithm that works with iteration. I am sure you would opt for the latter. Use loops to help you control a code that requires several runs. Debugging a loop with 20 repetitions is better than debugging 20 blocks of code with one repetition. 

Avoid the unnecessary: YAGNI 

You Aren’t Going to Need It is the full version of YAGNI. It is very simple to understand as it stresses on the present instead of the future. YAGNI states that you do not need to add a code for something that isn’t needed today. 
Coding for additional features that would never be used by the project is simply a waste of time, so why do it? Why solve an issue that hasn’t even become an issue? When you avoid these unnecessary coding habits, you will have a clean code.

Individualise behaviour: COI 

COI stands for Composition over Inheritance. This principle tells you to design objects based on what they are and not on what they are. To understand this, let us take the example of objects with behaviours, they should contain instances of only those objects with individual behaviours. These objects should not inherit a class, neither should they be given new behaviours. 

You may be wondering why, the answer is simple. You would be faced with two problems, one would be the hierarchy would become a mess and you would also lose flexibility that defines special-case behaviours. 

Establish a single responsibility for each class and module 

This principle states that each class and module should only be responsible for one functionality feature. Inundating a class with too many features would only complicate things and impede on the overall functionality, since you won’t be able to add any more additional features in the future. 

If you already have done something like this by overloading classes and modules, all you have to do is refactor and break them up into smaller pieces. 

Separate the concerns 

Separating the concerns states that while designing a program you ought to have different containers, which cannot become accessible to one another. 

The Model-View- Controller design is the prime example of this principle as it separates the program in three layers of data, logic and page displays. The result of this separation is that the code becomes extremely easy to debug and you can rewrite the code, without any worry of it the data and logic being affected.

Emphasise on documenting 

Proper documentation can be a life-saver, especially in coding. By documenting, I mean you have to add comments for explaining objects, for enhancing variable definitions and for making the functions relatively easy to understand. 

Imagine your future self coming back to the present code to perform a bug fix, would you not be thankful for the extra effort you put in now because then you would not have to go through each  line to understand the functionality of them. So yes, documenting helps in creating a cleaner code.  

Focus on consistency 

This principle does not really tell you how to code, rather it tells you to stick to the way you are already doing it. Consistency means practising the same techniques and methods through the code. This makes it easy to identify potential problems. 

However, there could be instances when you have to deviate from the consistent pathe you have set, and in that scenario, you can simply add a comment, like we discussed in the previous point, so that you and other developers know what happened and why. 

By following all of these you would end up with a code that is complete, concise, clear and organised. And that is the definition of a clean code. 

Coming to the crescendo, why is clean code important?

There is an open book with the points highlighting the importance of clean code written on top of it.


Now that you know how to differentiate between a clean code from the dirty and also have an awareness as to how to achieve that level of cleanliness, you must be wondering why to go to such lengths, when your old way worked just fine.

As an answer, let me just say two things; 

  • One is that fine should not be a target any one of us should be aiming for and certainly not something we should settle at.
  • And secondly, if something is working in the present, does that guarantee it would work in the future?

Don’t think that I am done explaining, not by any means. I have a long list of benefits that arise out of clean code and these will explicitly answer the 'why clean code is important’ question. So, let us begin. 

Clean code lets you read, modify and refactor with ease 

Like I mentioned in the previous section, writing clean code means writing a code that is simple, clear and easy to understand. It should not be overly complicated, without unnecessary details and repetitions throughout. This is important because your code would have to be revisited multiple times by you and other developers and it ought to be clear and concise.

You might be comfortable with your code now, imagine a month later, a junior developer has to refactor it, would he be able to apprehend it? If not, then you would have a problem. Even bug fixes would become a problem. Making a change in a section would become complicated because you would not be sure how it would have an impact on a different section, simply because you cannot read well enough to understand. 

Clean code lets you maintain with ease

Code isn’t something that is going to become redundant with the next wave of products, it is going to be there for decades, if you want it to. With that long a time span, it is evident that there are going to be issues with it. It’s sort of similar to a machine that has been working for a long time. Some parts of it would need to be oiled, some would need repairs and some would have to be changed altogether over time. Your code is just like that. 

Now if you have a messy code, and there is a bug to fix, it would take ages for your developers to figure out where the problem is and then additional time to finally fix it. This is also why many developers shy away from trying to read and apprehend an existing code and lean towards writing a new one and that shouldn’t be the case. With a clean code, it most definitely wouldn’t be. 

You would save so much time. Instead of working to solidify an existing dirty code, you could actually devote time to testing and development to improve your site’s overall functionality and appeal. So, clean code is important because it allows you and your developers to understand a code that has been written and refactored by a bunch of different developers and that saves you crucial time and effort, which makes you money. 

Clean code lets you test with ease

When we cook, we keep doing the taste test to know whether the flavours are going in the right direction or not. If we do that everyday for breakfast, lunch and dinner, should it not be done for software development as well. 

It most definitely should be. Web development undergoes both manual and automated testing and these tests are highly dependent on your code. The cleaner the code is, the better the outcome can be evaluated. With a messy code, how would you be able to find the source of the failure?

Since testing paves the way for an improved quality of code, improved pace of the team and a shrunken number of defects, you better start taking it seriously, and a cleaner code is the start.

Clean code lets you find your own rhythm 

When you write a piece of code, you are going to be putting in some effort. If a year down the line, another developer isn’t able to comprehend your writing, he would delete it and write a new code himself. Isn’t that a wasted effort?

A cleaner code would never let that happen. Cleanliness mandates a system that has to be followed and it could be whatever you want it to be. When you are writing a clean code, you would automatically find a rhythm, a system, technique that works for you and it would resonate throughout your work. Now, what would that do?

One it would have your imprint all over it, making it your masterpiece to be preserved forever, much like a Monet (excuse my exaggeration).
And the next developer at work would be able to identify the rhythm and understand it, he might even adopt it. 

Your rhythm would lead to consistency that would help in better management of the code and it would save you and the organisation a lot of time in the future.

Clean code lets you scale with ease 

Nothing remains stagnant in life. We as people start experiencing growth from the day we are born. The same is the case with web applications which leads me to the point of scalability. 

Any product or service that you provide would have to be taken to the next level some day. For that to happen, you would need to come back to the code base. If that is well documented and clean, the scaling of the project would become a breeze. If not, I don’t think I have to reiterate myself. The new developers and engineers would definitely have a lot on their plate.

The code is the foundation of any website or application, if that isn’t strong enough, can you even think about building anything else on top of it?

Clean code lets your developers be content 

Well, this one is something that has been felt by our developers. You could call it a personal advantage, if you may. 

Have you ever indulged in spring cleaning? When you say goodbye to all the mess and unnecessary things that you have accumulated throughout the year, do you not feel great, on top of the world? Does your home not feel like it has been purified to its very core? For me, it does feel like that. I am at my most content then, even more than Monica, when she scraped clean Joey and Chandler’s apartment to its last inch. 

For developers, the code is like their home, the cleaner it is, the better they are going to feel. The contentment they feel would eventually translate in their work, which would benefit your customers and you. A win-win for all. 

Once you have ensured that clean code is written, it is equally important to understand the significance of code review, incorporate healthy code review approaches, enabling proper collaboration between designers and developers during code review.

Conclusion 

I think I have said it all. Being messy does not work for anyone. You might have become comfortable with the mess, you might even have found a system that works for the mess. But would it work for the next developer, who steps in your shoes? Can you be absolutely certain that you would always be able to apprehend every word you have written in the code? 

Language is an art and so is creating something wonderful out of it. Being a writer, even if it is code that you write, you are an artist and you would want to be proud of your work. And you can’t be proud of a mess, so start amending the code to a cleaner version, if you haven’t already. Who knows there might just be a reward waiting for you at the end of it.

Subscribe

Ready to start your digital transformation journey with us?

Related Blogs

Debunking 6 Common Software Testing Myths

Common%20Misconceptions%20about%20Testing.png

A flawless product delivery requires a perfect combination of both development and testing efforts. Testing plays a vital role in…

With Ant Design, Create React Components Like a Pro

With%20Ant%20Design%2C%20Create%20React%20Components%20Like%20a%20Pro.png

Most enterprise-grade solutions depend on the React stack to create a robust platform for improved delivery and performance. React is one…

Boost developer productivity with Chakra UI

What%20is%20a%20chakra%20%281%29.png

React component libraries are helpful tools in creating stunning interfaces for react-based applications. Though each website component…