This article summarises part of a presentation I gave in 2017, after twenty years as a professional software developer.
One approach to learning how to write better code starts with specific software maintenance tactics. These three activities result in better code:
- remove code - don’t maintain what you don’t need
- refactor code - continually improve code as you raise your standards
- improve coding style - adopt a sense of good taste.
First, learn how: read about them, talk about them, and practice. Then learn how to do them systematically. Then do them more, by broadening their scope.
How many reasons to remove code can you discover? Start with these three reverse caption competitions: choose your meme!
Friends don’t let friends maintain dead code!
Go and delete it… you ain’t gonna need it!
Domain knowledge is an asset; code is a liability!
As a related skill, learn to use static analysis tools to hunt dead code, and practice thinking about class-level dependencies. And don’t forget to celebrate every 100 lines you remove.
Refactor code that smells
Dead code may have the worst code smell, but other code smells lurk in every codebase. Read the books and blogs that teach you about different code smells, and practice finding them with other coders. Pair programming and other kinds of code review give you plenty of opportunities to do this collaboratively. When you find code smells, actually fix them.
Get good at refactoring. Always focus on making refactorings as safe as possible, starting with unit tests that fail as soon as you do something unsafe, and reverting those changes. If you focus on safety, and do it a lot, you’ll end up with speed, in the coding version of the maxim slow is smooth, and smooth is fast.
Improve coding style
As well as identifying problematic code, you can also stop writing it in the first place. To do this, agree a team coding style and apply it as strictly as possible. In practice, as strictly as possible starts with non-negotiable automatic formatting, ideally as you type.
The cognitive load of reading messy code slows you down; total consistency fixes that. But coding style concerns much more than formatting. Go beyond code formatting and experiment with naming, paradigm, and other conventions. Reflect on techniques that work by asking, ‘what if we did this everywhere?’ Then update the team coding standard, refactor, and repeat.
Discover the difficulty
These three techniques represent obvious advice that you can easily apply, in the same way that you might find running or cooking easy. The challenge lies less in starting than in continuous improvement, and in dealing with situations such as more legacy code than you can ever read, let alone refactor. Learning to become a better coder by writing better code ultimately means embracing the idea that you can always get better, and having the discipline to keep on learning how.