7 Tips To Write Clean And Better Code in 2020

Software engineering is not just all about learning a language and building some software. As a software engineer or software developer, you are expected to write good software. So the question is what makes good software?. Good software can be judged by reading some piece of code written in the project. If the code is easy to understand and easy to change then definitely it’s a good software and developers love to work on that.

7-Tips-To-Write-Clean-And-Better-Code-in-2020

It’s a common thing in development that nobody wants to continue a project with horrible or messy code (It becomes a nightmare for sometimes…). Sometimes developers avoid writing clean code due to deadline pressure. They rush to go faster but what happens actually is they end up with going slower. It creates more bugs which they need to fix later going back on the same piece of code. This process takes much more time than the amount of time spent on writing the code. A study has revealed that the ratio of time spent reading code versus writing is well over 10 to 1.



Ratio-of-Time-Spent-Reading-Code-Versus-Writing

It doesn’t matter if you are a beginner or an experienced programmer, you should always try to become a good programmer (not just a programmer…). Remember that you are responsible for the quality of your code so make your program good enough so that other developers can understand and they don’t mock you every time to understand the messy code you wrote in your project.

What Makes a Clean Code: Before we discuss the art of writing clean and better code let’s see some characteristics of it…

  1. Clean code should be readable. If someone is reading your code they should have feeling of reading a poetry or prose.
  2. Clean code should be elegant. It should be pleasing to read and it should make you smile.
  3. Clean code should be simple and easy to understand. It should follow single responsibility principle (SRP).
  4. Clean code should be easy to understand, easy to change and easy to taken care of.
  5. Clean code should run all the tests.

“Clean code is simple and direct. Clean code reads like a well-written prose. Clean code never obscures the designer’s intent but rather is full of crisp abstractions and straightforward lines of control.”
-Grady Booch (Author of Object-Oriented Analysis and Design with Applications)

How to Write Clean and Better Code?

1. Use Meaningful Names

You will be writing a lot of names for variables, functions, classes, arguments, modules, packages, directories and things like that. Make a habit to use meaningful names in your code. Whatever names you mention in your code it should fulfill three purposes…what it does, why it exists and how it is used. For Example:

int b; // number of users.

In the above example, you need to mention a comment along with the name declaration of a variable which is not a characteristic of a good code. The name that you specify in your code should reveal it’s intent. It should specify the purpose of a variable, function or methods. So for the above example, a better variable name would be:- int number_of_users. It may take some time to choose meaningful names but it makes your code much cleaner and easy to read for other developers as well as for yourself. Also, try to limit the names to three or four words.

2. Single Responsibility Principle (SRP)

Classes, Functions or methods are a good way to organize the code in any programming language so when you are writing the code you really need to take care that how to write a function that communicates it’s intent. Most of the beginners do this mistake that they write a function that can handle and do almost everything (perform multiple tasks). It makes your code more confusing for developers and creates problems when they need to fix some bugs or find some piece of code. So when you are writing a function you should remember two things to make your function clean and easy to understand…

  1. They should be small.
  2. They should do only one thing and they should do it well.

The above two points clearly mention that your function should follow single responsibility principle. Which means it shouldn’t have nested structure or it should not have more than two indent level. Following this technique make your code much more readable and other developers can easily understand or implement another feature if your function fulfills a specific task.
Also, make sure that your function should not have more than three arguments. More arguments perform more tasks so try to keep the arguments as less as possible. Passing more than three arguments makes your code confusing, quite large and hard to debug if any problem would be there. If your function has try/catch/finally statement then make a separate function containing just the try-catch-finally statements.
Take care of your function name as well. Use a descriptive name for your function which should clearly specify that what it does.

Example:

function subtract(x, y) {
    return x - y;
}

In the above example the function name clearly shows that it’s purpose is to perform subtraction for two numbers, also it has only two arguments. Read more about writing a good function from the link 7 Common Programming Principles That Every Developer Must Follow and SOLID Principle.


3. Avoid Writing Unnecessary Comments

It’s a common thing that developers use comments to specify the purpose of a line in their code. It’s true that comments are really helpful in explaining the code what it does but it also requires more maintenance of your code. In development code move here and there but if the comment remains at the same place then it can create a big problem. It can create confusion among developers and they get distracted as well due to useless comments. It’s not like that you shouldn’t use comments at all, sometimes it is important, for example…if you are dealing with third party API where you need to explain some behavior there you can use comments to explain your code but don’t write comments where it’s not necessary.
Today modern programming languages syntax are English like through and that’s good enough to explain the purpose of a line in your code. To avoid comments in your code use meaningful names for variables, functions or files.

Good code is its own best documentation. As you’re about to add a comment, ask yourself, “How can I improve the code so that this comment isn’t needed?” Improve the code and then document it to make it even clearer.
-Steve McConnell

4. Write Readable Code For People

A lot of people especially beginners make mistake while writing a code that they write everything in a single line and don’t give proper whitespace, indentation or line breaks in their code. It makes their code messy and difficult to maintain. There’s always a chance that another human will get to your code and they will have to work with it. It wastes other developers’ time when they try to read and understand the messy code. So always pay attention to the formatting of your code. You will also save your time and energy when you will get back to your own code after a couple of days to make some changes. So make sure that your code should have a proper indentation, space and line breaks to make it readable for other people. The coding style and formatting affect the maintainability of your code. A software developer is always remembered for the coding style he/she follow in his/her code.

filter_none

edit
close

play_arrow

link
brightness_4
code

// Bad Code
class CarouselRightArrow 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> );}};
  
// Good Code
class CarouselRightArrow 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>
    );
  }
};

chevron_right


Code formatting is about communication, and communication is the professional developer’s first order of business.
-Robert C. Martin (Uncle Bob)

5. Write Unit Tests

Writing Unit test is very important in development. It makes your code clean, flexible and maintainable. Making changes in code and reducing bugs becomes easier. There is a process in software development which is called Test Driven Development (TDD) in which requirements are turned into some specific test cases then the software is improved to pass new tests. According to Robert C. Martin (Uncle Bob), the three laws of TDD demonstrate…

  1. You are not allowed to write any production code unless it is to make a failing unit test pass.
  2. You are not allowed to write any more of a unit test than is sufficient to fail, and compilation failures are failures.
  3. You are not allowed to write any more production code than is sufficient to pass the one failing unit test.

Test-Software-Developement

After I jumped on board the unit testing bandwagon, the quality of what I deliver has increased to the point that the amount of respect I get from my colleagues makes me feel awkward. They think I’m blessed or something. I’m not gifted or blessed or even that talented, I just test my code.
– Justin Yancey, Senior Systems Development Engineer, Amazon

6. Be Careful With Dependencies

In software development, you really need to be careful about your dependencies. If possible your dependencies should always be a singular direction. It means….let’s say we have a kitchen class which is dependent on a dishwasher class. As long as the dishwasher doesn’t also dependent on the kitchen class this is a one-directional dependency. The kitchen class is just using the dishwasher but the dishwasher doesn’t really care and anyone can use it. It doesn’t have to be a kitchen. This example of one-directional dependency is easier to manage however it’s impossible to always have one-directional dependency but we should try to have as many as possible. When dependency goes in multiple directions, things get much more complicated. In bidirectional dependency both the entities depend on each other, so they have to exist together even though they are separate. It becomes hard to update some systems when their dependencies don’t form a singular direction. So always be careful about managing your dependencies.

7. Make Your Project Well Organized

This is a very common problem in software development that we add and delete so many files or directories in our project and sometimes it becomes complicated and annoying for other developers to understand the project and work on that. We agree that you can not design a perfect organization of folders or files on day one but later on, when your project becomes larger you really need to be careful about the organization of your folder, files, and directories. A well-structured folder and file make everything clear and it becomes easier to understand a complete project, search some specific folder and make changes in it. So make sure that your directory or folder structure should be in an organized manner (Same applies for your code as well).

Best Books For Understanding How to Write Clean and Better Code:



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

4


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.