How to improve the quality of code?

Many junior developers get feedback that they need to improve the quality of their code. But quality of code is a vague term. This feedback is not directly actionable. Code quality encompasses many aspects like - extensibility, modularity, efficiency, maintainability, reusability etc. So where do you start? How do you know if you are producing good quality code? Without knowing that, you cannot improve your code quality.

There are some very simple ways to know. If you ask the below questions every time you write a piece of code, you can easily identify whether your code stinks or not. And if you fix them, your code quality will improve substantially.

1. Is the code repetitive?

Repetitive code is bad. For obvious reasons like, if you change at one place, you have to repeatedly modify it at other places as well. If you miss something, then you will introduce bugs.

But more fundamentally, even a few lines of repetitive code is a very strong indicator that your underlying design pattern is flawed. i.e. how your logic is broken down into modules - classes, interfaces, functions, components etc is not optimal.

2. Is the code testable?

Untestable code is very difficult to modify without introducing bugs. That is why testability of code is very important. But an untestable code and difficulty in mocking are indicators of deeper issues in your code like coupling between your code modules is strong and you are not passing dependencies properly.

By mastering dependency injection, you can solve this problem very well.

3. Is the code efficient?

Inefficient code leads to poor performance of the functionality. It wastes resources and eventually costs more. Common indicators of these are - poor choice or use of data structures, incorrect handling of lifecycle of resources or just bad algorithms.

Most times, simple time/space complexity analysis of your core functions can help you identify the performance issues. In remaining cases, you need to do extensive performance testing.

Okay, but what about ___ ?

If you address the above 3 problems, your code will already be ~95% better. After that, there is a long tail of remaining problems like extensibility of interfaces, error handling, better naming, atomicity of classes etc. But in my opinion, it takes experience of writing and maintaining software systems for a long time to get better at these.