DEV Community

Cover image for How to write clean and readable code
Emmanuel Echefu
Emmanuel Echefu

Posted on

How to write clean and readable code

Introduction
Writing clean and readable code is essential for any developer. It makes your code easier to understand, debug, and maintain. It also makes it more likely that other developers will be able to contribute to your project.

In this blog post, we will discuss some tips for writing clean and readable code. We will cover topics such as:

  1. Using descriptive variable names
  2. Formatting your code consistently
  3. Commenting your code
  4. Using functions and modules
  5. Avoiding duplication
  6. Using a consistent coding style
  7. Using proper indentation
  8. Using meaningful names for your files and folders
  9. Using comments to explain what your code is doing
  10. Testing your code thoroughly
  11. Using a version control system

By following these tips, you can write code that is easy to understand and maintain.

  • Descriptive variable names
    Image description
    One of the most important things you can do to write clean and readable code is to use descriptive variable names. This means using names that accurately reflect the purpose of the variable.
    For example, instead of using a variable name like x, you could use a name like productPrice. This would make it clear to anyone reading your code what the variable is used for.

  • Formatting your code consistently

Image description
Another important tip for writing clean and readable code is to format your code consistently. This means using the same indentation, spacing, and line breaks throughout your code.
Consistent formatting makes your code easier to read and understand. It also helps to prevent errors, as you are less likely to accidentally mistype a variable name or forget to add a semicolon.

  • Commenting your code

Image description
Comments are another important tool for writing clean and readable code. Comments can be used to explain what your code is doing, why you are doing it, and how it works.
Comments can be especially helpful for complex code or code that you have not written in a while. They can also be helpful for other developers who need to understand your code.

  • Using functions and modules

Image description
Functions and modules are a great way to break down your code into smaller, more manageable pieces. This makes your code easier to read, understand, and maintain.
Functions and modules can also help to improve performance, as they can be compiled and optimized separately.

  • Avoiding duplication

Image description
Avoiding duplication is another important tip for writing clean and readable code. Duplication occurs when you have to write the same code multiple times in your program.
Duplication can make your code difficult to read and maintain. It can also lead to errors, as you may accidentally make a change to one copy of the code but forget to make the same change to the other copies.
There are a number of ways to avoid duplication, such as using functions and modules. You can also use a code editor that supports code folding, which can help to hide duplicate code.

  • Using a consistent coding style

Image description
Using a consistent coding style can make your code look more professional and will make it easier for other developers to read and understand. There are a number of different coding styles that you can use, but it is important to choose one and stick with it.

  • Using proper indentation

Image description
Proper indentation can help to make your code easier to read and will also help to prevent errors. When you indent your code, you are visually grouping related statements together. This can help you to understand the flow of your code and can also help to prevent errors, as you are less likely to accidentally mistype a variable name or forget to add a semicolon.

  • Using meaningful names for your files and folders

Image description
Using meaningful names for your files and folders can help you to find your code quickly and easily. When you name your files and folders, use names that accurately reflect the contents of the file or folder.

  • Using comments to explain what your code is doing
    Comments can be used to explain what your code is doing. This can be helpful for other developers who need to understand your code and can also be helpful for you to understand your code in the future.
    When you write comments, be sure to explain what the code is doing and why you are doing it. Avoid writing comments that simply repeat what the code is doing.

  • Testing your code thoroughly

Image description
Testing your code thoroughly can help to ensure that your code works correctly and will also help to prevent errors. When you test your code, be sure to test all possible scenarios.

  • Using a version control system Using a version control system can help you to track changes to your code and can also help you to revert to a previous version of your code if something goes wrong

Conclusion

By following the tips in this blog post, you can write clean and readable code that is easy to understand, debug, and maintain. This will make your code more enjoyable to work with and will help you to be more productive as a developer.

In addition to the tips listed in this blog post, there are a number of other things you can do to improve the readability of your code. For example, you can use a linter to check your code for errors and style violations. You can also use a code review tool to have other developers review your code before you commit it to your project.

By taking the time to write clean and readable code, you can make your code more maintainable and easier to understand. This will make you a more productive developer and will help you to create better software.

About Me

Image description
I am a web developer from Lagos, Nigeria. I enjoy building everything from small business sites to rich interactive web apps.
I specialize in custom web theme development and love what I do. Since beginning my journey as a web developer when I was 5 (Yes i am a Gen-Z), I've done remote work for agencies, consulted for startups, and collaborated with talented people to create digital products for both business and consumer use.
I'm quietly confident, naturally curious, and perpetually working on improving my chops one design problem at a time.

Top comments (10)

Collapse
 
brense profile image
Rense Bakker

Good article, however I don't fully agree about commenting your code. If you feel like the code isn't self explanatory, I think it's better to figure out what you can do about the actual code... Maybe you need to split it into seperate functions, or use better variable names etc. Using a comment to explain the code feels like a shortcut that leads to unclean code. There's one exception, when your code represents complex business logic that will not be easy to understand for another developer, you should add a comment with a short explanation, or even a link to documentation that explains why the business rules are the way they are.

Collapse
 
ajebodev profile image
Emmanuel Echefu

I agree with you that comments should not be used as a crutch to make up for poorly written code. However, I also believe that comments can be a valuable tool for explaining complex code or providing context for why certain decisions were made.

As you mentioned, one of the best ways to improve the readability of your code is to split it into smaller, more manageable functions. This can make it easier to understand the overall flow of the code and identify any potential problems. Additionally, using clear and descriptive variable names can also help to make your code more self-documenting.

However, there will always be times when your code is simply too complex to be easily understood without additional explanation, like you rightly alluded. In these cases, a well-written comment can be a lifesaver. For example, if you are using a particular algorithm or data structure that is not well-known, a comment can provide a brief overview of how it works. Additionally, if your code is implementing a complex business rule, a comment can explain the rationale behind the rule.

Of course, it is important to use comments sparingly. Too many comments can make your code difficult to read and maintain. However, when used judiciously, comments can be a valuable tool for improving the readability and maintainability of your code.

Side note; here are some additional tips for writing effective code comments:

  • Keep comments brief and to the point.
  • Use clear and concise language.
  • Avoid jargon and technical terms.
  • Make sure your comments are accurate and up-to-date.
  • Use comments to explain why you are doing something, not just what you are doing.

By following these tips, you can write code comments that are clear, concise, and helpful. Thanks for the engagement.

Collapse
 
rgaiken profile image
rgaiken

IMO comments that explain what the code is doing should generally be replaced by easier to read code (with exceptions eg if performance needs prevent it).

Comments that explain why the code is the way it is are generally much more helpful

Collapse
 
cubiclesocial profile image
cubiclesocial

Another valid reason to write comments is to explain security related code. If some piece of code exists to prevent XSRF, SQL injection, or some other thing that should probably remain unmodified, then that's the place for a comment explaining why that code exists in the first place and why it shouldn't be modified without first considering the broader ramifications. Defensive code against exploits is fairly random looking, slightly out of place code that looks like "it doesn't belong / needs to be modified or optimized" to the casual dev just happening upon the code. A comment at those points in the code saves a lot of repeated explaining to other people who aren't "in the know." Such comments also have a transparent "nothing up my sleeve" approach to system security, which builds trust.

Collapse
 
brense profile image
Rense Bakker

If a piece of code is that critical for security, there should be unit tests for it, that will start to scream at the dev when they modify it.

Thread Thread
 
ajebodev profile image
Emmanuel Echefu

Yes, that's a good idea. Unit tests are a great way to ensure that critical code is working as expected. When a developer makes a change to critical code, the unit tests should fail. This will alert the developer that they have made a change that could potentially introduce a security vulnerability.

Collapse
 
cubiclesocial profile image
cubiclesocial

Some code duplication is okay. Here's a good rule of thumb to follow:

  1. Write code inline.
  2. The second time you need to write/use the same code, make a mental note that you are duplicating code. If, at this point, you can see yourself needing that code over and over and over again, then refactor here. Otherwise, carry on by duplicating the code.
  3. The third time you need to write/use the same code, it's probably time to consider refactoring the code into a function, class, or a formal library.

In short, one duplication isn't all that bad. It happens. Two duplications is where it's probably time to refactor the code as it is an indicator of something that could end up getting fairly ugly rather quickly.

However, there are a couple of exceptions to the above rule of thumb. The first is that having libraries depend on other libraries depend on other libraries depend on other libraries depend on other libraries depend on other libraries depend on other libraries depend on other libraries depend on other libraries depend on other libraries depend on other libraries depend on other libraries depend on other libraries depend on other libraries depend on other libraries depend on other libraries causes performance and resource usage problems. You want your application function call stack to be pretty flat. If you import a whole library that imports a bunch of other libraries just to call one teensy tiny function and that function has no particular dependencies on anything else (e.g. it is static or close enough to static), it is far better to copy that one function into your own code than to import a gazillion libraries and waste a ton of system resources. Could you have 10 copies of the same function across multiple libraries floating around as a result? Sure. But the call stack stays flat and resource usage is minimized.

The second exception to that rule of thumb is that application performance is a reason to NOT refactor inlined duplicated code into their own functions. Calling a function has significant overhead whereas inline code, even repeated, can be many times faster when run inside a tight loop. You need to be doing some serious data/number crunching in a loop or writing a virtual machine for this to be a problem though. Code readability is generally a good priority to have. Regardless, knowing when to not refactor is just as important as knowing when to refactor.

Collapse
 
ajebodev profile image
Emmanuel Echefu

Rightly stated.... ;) Do read up my other posts if it's not too much trouble, ( dev.to/ajebodev/debugging-code-a-s... that's a link to my most recent post). Have a great day, look forward to further interactions.

Collapse
 
villelmo profile image
William Torrez

My code don't have logic

Image description

Collapse
 
ajebodev profile image
Emmanuel Echefu

Okay, do you need help?

  1. Read your code carefully. Make sure that you understand what each line of code is doing.
  2. Look for variables. Make sure that you have defined all of the variables that your code needs.
  3. Look for conditional statements. Make sure that you have used conditional statements to make decisions in your code.
  4. Look for loops. Make sure that you have used loops to repeat code a certain number of times, or until a certain condition is met.

If you still need help,

  • Start by breaking down the problem into smaller steps. Once you have a good understanding of the problem, you can start to write code to solve each step.
  • Use variables to store data. This will make your code more readable and easier to maintain.
  • Use conditional statements to make decisions. This will allow your code to react to different input.
  • Use loops to repeat code. This will save you time and make your code more efficient.

If you don't mind I'd like to hear updates from you.