15 tips to write clean code

Nowadays, almost anyone can code. Computer languages have become such user-friendly that with a minimum of learning any self-made enthusiastic can makes a program to solve a problem using a computer.

However, it is not the same coding as writing a clean code. Bad coding may work, but it is difficult to understand by others, show a complexity that should not give more insights into the problem that solves, and frustrate anyone that tries to analyze it.  It is true that it takes longer to write a clean code than a sloppy one, but in the end, and even for the same person that is writing the code a clean solution saves everyone time, effort, and ultimately money.

Even if you are not a professional but an enthusiast of programming, there is always room to learn to be a better coder. And writing cleaner code is something that can be learned. It is independent of the programming language you are using while depending on language-agnostic principles.

Let’s start with some basic principles and build from those solid foundations. 

KISS

The first principle to writing clean code is resumed in the acronym KISS: Keep it simple, stupid. It was formulated originally as a design principle in 1960 but applies to most systems, and life itself. 

It can be resumed as “any system should be kept as simple as possible, avoiding unnecessary complexity”. Applying it to code, the programmer should ask himself if the program is written in the simpler way possible.

Multiple job opportunities.
One code challenge.

Get rid of repetitive hiring processes for all the positions you apply to, and access many job offers by taking a single real-world assessment.

DRY

This is the principle “Do not Repeat Yourself”, related to the minimalist design philosophy. It states that every piece of code must have a unique, unambiguous, and authoritative representation within the code base. In a wordplay, when you are not DRY, your WET: Writing Everything Twice, and Wasting Everyone's Time.

YAGNI

The YAGNI principle stands for “You Aren't Gonna Need It”. It means that you should not add functionality within the code unless you are going to use it. As part of the Extreme Programming methodology, YAGNI looks to improve software quality and responsiveness to customer requirements. Of course, this principle should be used together with continuous refactoring, unit testing, and integration in order to give to the user exactly what he needs.

Composition over inheritance

You should design your types over what they do, instead of over what they are. In other words, classes should achieve polymorphic behavior and code reuse by their composition (by containing instances of other classes that implement the desired functionality) rather than inheritance from a base or parent class. Inheritance forces you to build a taxonomy of objects early on in a project, rendering your code inflexible for changes later on.

Favor Readability

Ok, in the end, a machine will read and process the code, but that is not an excuse to make it obscure to other programmers. Readability is particularly important when you are working with others on a bigger project and your code needs to be inserted in a bigger frame. Concise code is good, as long as other humans can understand it.

You can make your code available to others by placing common numbers into well-named constants and creating long names instead of shorter ones for your procedures.

Practice consistency

One of the most important principles in clean coding: if you have decided to do something a certain way, stick to it throughout the entire project. If for some reason you need to change your coding style, it is better to explain why you are making it different in a comment to the people that are following your code. 

Magic Numbers

If you are using “magic numbers” (numbers with no clear meaning), you should explain why to other people who are reading your code. That value may have a specific purpose within the project, but if you don't assign it to a meaningful variable, no one else will know. 

Deep Nesting

This is something that obscures your coding and should be avoided because nested loops are difficult to understand. It is better to extract all loops into separate functions instead.

OK, it is valid coding to use nested loops to get the values from an array of another array that contains another array, but it is not elegant, nor a clean code solution. Functions, on the other hand, do the same trick in a cleaner, easier to read, easier, less repetitive, and reusable way.

Comments

It is a good coding policy to write comments within the code that helps others to understand what you have done, but sometimes commenting is used as an excuse for not making good, clean, and self-explanatory code.

If you need to comment on your code, it means that it is not clear or simpler enough to be understood by your peers, so try to write the program lines in a way that no comments are needed to follow your coding strategy. Remember that the best comments are the ones that can be erased and yet your code is clean enough to be understood.

Avoid Larger functions

If a function or a class is too large, it is probably for the best to divide it into multiple instances. Whenever you use a shorter function it becomes reusable, cleaner, and easier to use and understand. 

Code repetition

Remember the DRY principle: if you repeat a part of your code more than once, it should be transformed into a function to call it when needed. This may look silly for simple operations, but still, it is a good, clean code principle. Making an individual function to do repetitive tasks is the better solution; also, reusable.

Variable Naming 

To write clean code, one key principle is to have style rules to name variables and functions. It is a convention that both function and variable must follow the naming standard rule that a name is supposed to begin with a small letter and every first letter of the next word will be uppercase. 

Of course, the compiler does not need those variables to be named that way, but humans do in order to get a better understanding of your code.

Meaningful names

Another important principle of clean code is the use of meaningful names. Variables, functions, and others must have a name related to their purpose, in order to clarify what this element is doing inside the program.

For instance, if we need a function that will get the user's bank information, a name like getUserInfo or something like that is not given the required information to the person that is reading the code. A cleaner code name for that function should be something like getUserBankInfo, to be more specific.

Use consistent verbs per concept

Another important naming convention: if we need a CRUD function, we use create, get, or update with the name using a consistent verb to state what the function does. For instance, if we need to get user info from the database, the name of the function could be something like userInfo, or fetchUser. But in order to be coherent with the concept, we should use getUser.

Capitalize constant values

Another convention to write clean code is to capitalize constant values. If you always use fully capitalized names for constants, a reader will know at a glance that you are defining a constant. This is called snake uppercase, meaning that all the letters will be uppercase, and an underscore will be used to separate words.

Avoid one-letter variable names

One-letter variables are a very bad idea within a code since the person who reads it will get easily lost. However, we can use one-letter variable names if there are actually not too relevant to the code itself, like the ones we use as counters while whiting a loop or something like that. 

Always favor descriptive over concise

Basically, this principle tells you that you should be as detailed as possible for any naming. Always assume that it is not the same a meaningful name than a detailed, meaningful name that expresses the meaning and porpoise of an element in a nutshell.

When you detailed the name of an element extensively, the code will become clearer for someone who is trying to understand it.

Some final words of advice

And that’s all the principles of clean code that we wanted to share with you. We hope that you start to take them into account when writing your programs, in order to become a better professional in this area of expertise. 

Remember that following this coding principle and conventions is like observing the good style guideline for programming. In the words of Robert C. Martin, “Clean code is simple and direct. Clean code reads like well-written prose. Clean code never obscures the designer’s intent but rather is full of crisp abstractions and straightforward lines of control.”

So we hope that you start to use this advice and guidelines right away, and next time we read some of your code we get delighted at how slick and clean is your programming. 

Master coding interviews for growing tech companies

Discover here the ultimate guide to coding interview processes. Find out how they work and how you can optimize yourself as a developer to attract the attention of tech companies and get better results in their coding interviews.

Related articles


Stay tuned: receive the latest product updates


Subscribe to our newsletter to keep up with the latest trends!