My previous post
highlighted some of the problems working with a legacy codebase (I agree with Michael Feathers that any code that doesn’t have tests is legacy code).
So how do we start refactoring in a situation like this?
Simply put, it is all about managing risk. You want to find the highest impact, smallest risk incremental improvements that you can make without too much effort.
Since we know that we read more code than we write, anything that makes code more readable is probably worthwhile and will make the code more maintainable.
So, how do you make code more readable? The first step for me was to get everybody on the same page by creating a style guide for Java and for Android.
Fixing your code style doesn’t necessarily make the code any better, but it does make it more readable.
The next step for us was to start creating a best practice guide for Android. There are a lot of things to keep in mind for performance and stability which can ultimately make or break the user experience. By documenting these, we give new developers a place to start and everybody a place to reference these points.
We also follow the idea of the boy scout rule, which can be summed up as “Leave any code you touch in a better state than you found it”.
This is of course a bit of a slippery slope. Some reviewers argue that it makes code reviews more difficult because it’s hard to see what changes was due to refactoring, and what was specifically related to your task. Personally I think having to work a bit harder in the peer review to make the code more maintainable is a perfectly fair trade-off. One way to make it even easier is to make sure that you separate refactoring changes into their own commits.
Of course, if you don’t have test coverage you have to be very careful with the type of refactoring you do and focus on low risk items.
Now that we have style guides, best practices and a plan to start refactoring, we need tho start enforcing it. The simplest way to do this is by starting to do peer reviews. Ideally, for styling, naming, etc, you should also get a CI server set up and running static analysis.
I tend to see a lot of pushback against peer reviews, but as long as you can create an environment where peer reviews can be constructive and can give feedback on the code without having people feel that they are being judged, there are no better way to drastically improve your code quality over time.
So, in summary, the low hanging fruit which you can start picking off without too much risk or effort:
- Create a style guide
- Create a best practice guide
- Do opportunistic refactoring. Refactor low risk items like styling, naming and big methods while you are working on the code.
- Start peer reviewing ALL code to make sure people adhere to style and best practice guides and that they are leaving the code in a better state than they found it in.