Tips for writing clean code

Writing clean, understandable, and maintainable code is a skill that every developer should master, don’t you agree? As elegantly put by the software engineer Martin Fowler, “Any fool can write code that a computer can understand. Good programmers write code that humans can understand”.

I know that sometimes it’s faster to write messy and unorganized code. After all, the code works, and that’s the whole point, no?! But when your code is easy to read, it is easier to make changes, saving you and your team a lot of time in the long run.

So here are some short and sweet tips, that you can easily incorporate, for writing clean code.

  • Create meaningful names - If a variable or function name requires a comment, you should take your time to rename it instead of leaving that comment there.
  • Use pronounceable names - if you can’t pronounce the name of a variable or function, consider changing it. It will also save you from sounding slightly off when you need to discuss that part of the code with your team.
  • Use searchable names for constants - Avoid having mysterious numbers or strings in your code. Instead, you should opt for constants with names that are easily searchable. If the constant changes, you only need to worry about changing its value in one place.
  • White short functions that only do one thing - Do you know the SOC principle? Functions are more understandable, readable, and maintainable if they only have one job. It’s typically easier to find bugs in short functions, and the code will also be more reusable.
  • Write good documentation - This is useful for future developers to understand better what your code is doing and why. And don’t forget that “future developer” can also be the “you” of a couple of weeks from now. So do your future self a favor and comment and document that code you are writing today.

Extra tip: If you want to go deeper into the clean code world, the book Clean Code: A Handbook of Agile Software Craftsmanship by Robert C. Martin is a great place to start. The book presents several practices and principles for writing clean code, and it has several case studies and exercises for you to practice.

Do you follow any of these tips? Is there any other tip that you can tell us about?

1 Like