Stopping complex code from sneaking into a project during code reviews
Mar 14, 2024
Anytime we add new, complex code to our project, we’re setting a trap for our future selves (and for our colleagues). Every time we have to deal with that complex code in the future we’re going to be paying a tax on our productivity from the added time it takes to work with that code. And the more complex our code is the more likely it is that we are going to accidentally introduce bugs into our project in the future.
Ideally, everyone would just never produce complex code to begin with. But we all know that’s not realistic 🙂 - so the best thing we can do is make sure we’re catching unnecessarily complex code before it’s merged. Today I want to look at how we can catch complex code during the code review process.
Before we dive into how we want to catch complexity during reviews we need to acknowledge something about complex code.
Not all complex code is made equal. Some code complexity is absolutely necessary because we’re using code to solve complex problems. This is essential complexity - it's the complexity needed to get the job done.
On the other hand, there's complexity that we introduce into our code that is not necessary. It can be eliminated from our code and we would still get the job done - this is accidental complexity.
When we think about catching complex code in reviews we just care about the accidental complexity - complexity that we don’t need to have in order to achieve the goals of the code.
There are a host of ways we could try to identify overly complex code being introduced in a PR - but I tend to think there are 4 things to look for that will catch the most harmful additions of excess complexity to your project.
You can look for other types of complexity during the review process, but if you’re able to check for these 4 aspects you should start cutting down on unnecessary complexity sneaking into your project.
We’ve set up our Sourcery code reviews to specifically check for unnecessary code complexity as a part of the review process (if you want to learn a bit more about how we do it under the hood we’ve written about it here).
We look for the 4 types of complexity risks I’ve described above, as well as a few others, and then help you understand how you can fix any unnecessary complexity in your code changes before you merge. This saves you from leaving any traps for your future self.
We’re working to build a better automated version of code reviews at Sourcery. Try it out on any of your GitHub repos or reach out to hello@sourcery.ai to learn more.