+593 99 022 3684 dime@hassler.ec

Writing clean code is not an easy task. It requires experimenting with different tips and practices. The problem is that there are so many practices and tips on this subject it can be overwhelming. As a result, it can be hard for a developer to choose those tips and practices worth following. Let’s make this task easier. In this article, we will first discuss some benefits of writing clean code. Then, we will take a look at six tips, or practices, for writing clean code developers use most often.

Table of Contents:

The benefits of writing clean code

1. Easier to start, or continue

2. Better for team onboarding

3. Easier to follow

Tips on writing clean code

1. Make code readable for people

2. Use meaningful names for variables, functions and methods

3. Let every function or method perform only one task

4. Use comments for clarification

5. Be consistent

6. Review your code regularly

Closing thoughts on writing clean code

The benefits of writing clean code

Let’s start by taking a look at some benefits writing clean code has. One of the main benefits is that clean code helps us minimize the time we need to spend reading and trying to understand the code. Messy code has the uncanny ability to slow down any developer and make his work much harder. The messier the code is, the more time developer needs to understand it enough he can work with. And, if the code is too messy, developer may decide to stop and start from scratch.

1. Easier to start, or continue

Let me demonstrate this on one simple example. Let’s say that we return to one of our projects after a very long time. Maybe, one of our previous clients got in touch with us and hired us for another work. Now, let’s also imagine that, back then, we were not writing the cleanest code under the sun, rather the opposite. Right after the first look, we see how bad and messy the code is. And, we can also already see how hard it will be to start where we left off.

As a result, we now must spend much more time on the project, than we would have to because we need to understand the code we wrote before. This is definitely not necessary. We could avoid it completely by writing clean code right from the beginning. Now, we have to pay for it. And, there is also some small chance that our old code is so messy or bad that we may decide to start from scratch. Our client will probably not be happy after hearing these news.

Clean code, on the other hand, usually doesn’t have this problem. Imagine the previous example with opposite conditions. Now, our previous code is clean and elegant. How long will it take to understand it? Maybe we will need to read the code for a few minutes to understand how everything works. In the end, it’s been a while since we wrote it. However, this time investment will be significantly smaller than in the first case. Our client will not even notice it.

This is the first benefit of a code written in a way that is in harmony with tips we will discuss. And, this is not true just for our own projects but also for the work of other developers. Clean code allows us to start much faster. We, or anyone else, don’t need to spend hours studying it. Instead, we can get right into the work.

2. Better for team onboarding

Another benefit of writing clean code is closely related to the first one. It allows for easier and faster adoption. What I mean is this. Let’s imagine that we need to hire another developer. How long will it take her to understand the code and learn how to work with it? It depends. If our code is messy and poorly written, she will need more time to get through it. On the other hand, if our code is clean, readable, comprehensible and simple, she will be able to start faster.

Some people may want to argue that this is not such a problem since we are there and we can help her. And, this is true. However, our help should be necessary only for a short time, day or two maybe three. However, it should not be a week or two or three. In the end, we decided to hire another developer to speed up our work, not to slow it down even more. Our goal was not burning more time by helping her learn to work with our code.

When we make the effort and write clean code, it will be easier for other people to follow it and work with it. Sure, we will still need to set aside some time to help every new developer learn about and understand our code. However, we talk about a few days, not weeks. Also, clean code will help us bring more developers to the team and help them all understand our code at once. Put simply, the cleaner the code is the easier it is to explain it and less is the misunderstandings.

3. Easier to follow

There is one thing we need to remember. Understanding and learning about how to work with code is one thing. However, this is only the beginning. We also need to make sure a developer is able and willing to follow our coding practices. Again, this will be easier to achieve with clean code, rather than messy. This is important because we want not only to write clean code, but to keep it that way, no matter how many people work with it. We need to think long-term.

One last thing related to this. What if one of our developers decides to not to follow current coding practices? This issue usually solves itself. Let’s say we have a group of people working on the same code base and one starts to deviate from standard style. Then, one of these three things will happen. First, the rest of the group will push that one developer to follow the standards. She will accept it because she doesn’t want to leave.

Second option is that the developer will actually convince the rest of the team to adopt and follow her coding practices. This may be a good thing if coding practices proposed by the developer is cleaner and brings better results. Writing and keeping our code clean doesn’t mean we should ignore any opportunities for improving it. Rather the opposite. I believe that we should always question our current practices and look for these opportunities for improvement.

So, if one developer deviates from our practices, and her practices are better, it may be better if we make the change, not her. I think we should never ignore someone’s practices before we examine and try them. There is always a room for improvement and we should keep looking for it. Finally, there is the third option. The developer will decide neither adopt our practices nor convince us to adopt hers. Instead, she will decide to leave the team.

Tips on writing clean code

Now, when we discussed some of the benefits of writing clean code, it is time to learn some tips which will help us do it. As we will see on the following lines, clean code embraces and follows certain practices. These practices are what makes our code cleaner, readable, more comprehensible and simpler. It is not necessary to implement all these practices. Implementing and following just one or two can be enough to bring positive results.

1. Make code readable for people

It is true that the code we write will be interpreted by machines. However, that doesn’t mean that we should neglect its readability and comprehensibility. There is always a chance that another human will get to our code, or will have to work with it. Even if we make our code inaccessible to others, we may want to get back to it in the future. For this reason, it is in our own interest to write our code in a way that will make it easy to read understand. How?

The easiest way is to use whitespace. It is okay to minify our code before we ship it. However, it is not necessary to write code that looks like minified. Instead, we can use indentation, line breaks and empty lines to make the structure of our code more readable. When we decide to embrace this practice, the readability and comprehensibility of our code can improve significantly. Then, a single look at our code can be enough to understand it. Let’s take a look at two simple examples.

Code:

// Bad
const userData=[{userId: 1, userName: 'Anthony Johnson', memberSince: '08-01-2017', fluentIn: [ 'English', 'Greek', 'Russian']},{userId: 2, userName: 'Alice Stevens', memberSince: '02-11-2016', fluentIn: [ 'English', 'French', 'German']},{userId: 3, userName: 'Bradley Stark', memberSince: '29-08-2013', fluentIn: [ 'Czech', 'English', 'Polish']},{userId: 4, userName: 'Hirohiro Matumoto', memberSince: '08-05-2015', fluentIn: [ 'Chinese', 'English', 'German', 'Japanese']}];

// Better
const userData = [
  {
    userId: 1,
    userName: 'Anthony Johnson',
    memberSince: '08-01-2017',
    fluentIn: [
      'English',
      'Greek',
      'Russian'
    ]
  }, {
    userId: 2,
    userName: 'Alice Stevens',
    memberSince: '02-11-2016',
    fluentIn: [
      'English',
      'French',
      'German'
    ]
  }, {
    userId: 3,
    userName: 'Bradley Stark',
    memberSince: '29-08-2013',
    fluentIn: [
      'Czech',
      'English',
      'Polish'
    ]
  }, {
    userId: 4,
    userName: 'Hirohiro Matumoto',
    memberSince: '08-05-2015',
    fluentIn: [
      'Chinese',
      'English',
      'German',
      'Japanese'
    ]
  }
];

Code:

// Bad
class CarouselLeftArrow extends Component{render(){return ( <a href="#" className="carousel__arrow carousel__arrow--left" onClick={this.props.onClick}> <span className="fa fa-2x fa-angle-left"/> </a> );}};

// Better
class CarouselLeftArrow extends Component {
  render() {
    return (
      <a
        href="#"
        className="carousel__arrow carousel__arrow--left"
        onClick={this.props.onClick}
      >
        <span className="fa fa-2x fa-angle-left" />
      </a>
    );
  }
};

2. Use meaningful names for variables, functions and methods

Let’s take a look at second tip that will help us write comprehensible and clean code. This tip is about using meaningful names for variables, functions and method. What does meaningful mean? Meaningful names are names descriptive enough that other people, and not just us, will be able to understand the purpose of the variable, function or method. In other words, the name itself should suggest what the variable, function or method is used for, or what it contains.
Code:

// Bad
const fnm = ‘Tom’;
const lnm = ‘Hanks’
const x = 31;
const l = lstnm.length;
const boo = false;
const curr = true;
const sfn = ‘Remember the name’;
const dbl = [‘1984’, ‘1987’, ‘1989’, ‘1991’].map((i) => {
  return i * 2;
});

// Better
const firstName = ‘Tom’;
const lastName = ‘Hanks’
const age = 31;
const lastNameLength = lastName.length;
const isComplete = false;
const isCurrentlyActive = true;
const songFileName = ‘Remember the name’;
const yearsDoubled = [‘1984’, ‘1987’, ‘1989’, ‘1991’].map((year) => {
  return year * 2;
});

However, there is something we should keep in mind. Using descriptive names doesn’t mean we are free to use as many characters as we want. A good rule of thumb is to limit the names to three or four words. If we need to use more than four words, maybe we are trying to do too many things at once and we should simplify our code. So, let’s use only as many characters as necessary.

3. Let one function or method perform only one task

When I started with coding, I used to write functions and methods that looked almost like a Swiss Army knife. They could handle and do almost anything. One of the consequences was that it was often hard to find a good names. Second, almost nobody except me knew what this or that function does and how to use it. Well, sometimes even I ran into problems. So, I had to write instructions. Third, these functions were sometimes quite unpredictable. I created a mess.

Then, someone gave this great advice. Let every function, or method, perform just one task. This simple advice changed everything and helped me write clean code, at least cleaner then before. From that moment, other people were finally able to understand my code. Or, they didn’t need as much time as they needed before. My functions and methods also become predictable. They always produced the same output given the same inputs. And, naming got much easier as well.

If you have a hard time finding descriptive names for your functions and methods, or you need to write lengthy instructions so other people can use them, consider implementing this practice. Let every function or method perform only one task. Implement this practice also if your functions and methods look and work like a Swiss Army knife. Trust me, this versatility is not an advantage. It is rather a disadvantage that can start to backfire in any moment.

Side note: this practice of letting every function, or method, perform only one task is called Single responsibility principle. This coding practice was introduced by Robert C. Martin as one of the five object-oriented design principles also known as SOLID . If you want to learn more about it, I recommend reading this article.
Code:

// Example no.1: Simple subtraction
function subtract(x, y) {
    return x - y;
}
// Example no.1: Simple multiplication
function multiply(x, y) {
    return x * y;
}

// Example no.1: Double numbers in an array
function doubleArray(array) {
  return array.map(number => number * 2)
}

4. Use comments for clarification

It doesn’t matter how hard we try to come up with meaningful names for our variables, functions and methods. Our code on its own is still not as clean and comprehensible as it could be. There are still some lines that require further explanation. The problem may not be that they are hard to understand or use. Instead, it may not make sense why we implement this or that function or method or why we created it in that specific way. Meaning, the history is still unclear.

Sometimes we may have to use rather unconventional approach to solve a problem because nothing else works or we don’t have enough time to come up with better solution. This can be difficult to explain with code. Using comments through our code can help us fix this problem. Comments can help us explain to other people why we wrote what we wrote, and why we wrote it in that specific way. As a result, other people will not have to guess.

What’s more, when we explain our reasons, other people may find a better way to solve the problem and improve the code. This will be only possible because they know what the problem is and what is the desired outcome. It would be much harder for others to create a better solution without knowing these information. Or, they may not even try it because they wouldn’t think there is a need for it. They could think that it was our intent.

So, whenever we find ourselves in a situation where we decide to use some hack, quick fix or unconventional approach, let’s use comments to explain why we did what we did. It is better to use one or two lines for a comment with explanation than to force people to guess.

That being said, we should use comments only when it is necessary, not to explain bad code. Writing endless lines of comments will not help us transform poorly written code into a clean code. If the code is bad, we should fix the problem by improving the code, not by adding set of instructions on how to use it. Clean code takes precedence over the use of shortcuts.

5. Be consistent

When we find specific coding practices or style we like, we should stick to it and use it everywhere. Using different coding practices or styles in different project is not a good idea. It is almost as useful and helpful as not using any coding practice or style at all. Going back to our old code will not be as smooth and natural as it could be. We will still need some time to understand the coding practice we used on that project before will can work with it.

The best thing to do is picking a set of coding practices and then sticking to these practices in all our projects. Then, it will be much easier to return to our older code and continue where we left off or improve it. What about experimentation? Trying new coding practices is a good thing. It can help us find better ways to do our work. However, it is better to experiment with different practices on separate experimental projects or exercises, not our main projects.

Also, when we decide to do some experiment, we should try that practice multiple times and on multiple examples. We should take the time to do that experiment thoroughly. Only when we are really convinced we like that practice and we feel comfortable with it, we should implement it. And, when we decide to do so, it is better to implement our new practice globally, in all our projects. Yes, this will take time, but it will force us to think about the change properly.

6. Review your code regularly

This is my final tip on writing clean code. Simply writing clean code is not everything. Our job is not done with the final semicolon. The next step is keeping our code clean. Clean code requires maintenance. When we write something, we should review on a regular basis, clean it up and try to improve it. Otherwise, if we don’t review and update our old code it will soon get outdated. Just like with our devices. If we want to keep them in the best shape we need to update them regularly.

The same is especially true for the code we work with daily. Code has the tendency to get more complex and cluttered with time, not simpler and cleaner. It is up to us to prevent this from happening and keep our code clean. The only way to do achieve this is by doing regular reviews of our code. In other words, we need to maintain it. This may not be necessary for projects we no longer care about or that have no future. For the rest of them, maintenance is part of our job.

Closing thoughts on writing clean code

And we are on the end of this article. These six practices, we discussed today, may not be the ones with the biggest impact or the most significant results. However, they are among those most frequently mentioned by experienced developers. That’s why I chose them. I hope that these practices or tips will be enough to help you get started with writing clean code. Now, like with everything, the most important thing is to get started. So, pick at least one practice and try it out.

Thank you very much for your time. And, until next time, have a great day!

Did you like this article? Please subscribe.

Are you on social media? Let’s connect! You can find me on Twitter and Dribbble.


Originally published at Alex Devero Blog.

Alex Devero

Modern Da Vinci. Designer & developer, blogger and entrepreneur. I’m minimalism and calisthenics lover.

 http://www.alexdevero.com

http://www.blog.alexdevero.com

Si continuas utilizando este sitio aceptas el uso de cookies. más información

Los ajustes de cookies de esta web están configurados para "permitir cookies" y así ofrecerte la mejor experiencia de navegación posible. Si sigues utilizando esta web sin cambiar tus ajustes de cookies o haces clic en "Aceptar" estarás dando tu consentimiento a esto.

Cerrar