˝Refactoring is a controlled technique for improving the design of an existing code base” — Martin Fowler.
Discipline and methodology are critical when refactoring.
We should refactor applying a series of small controlled steps. After each of these steps our tests should still be green.
This way, if we break something in the process we can easily roll back.
Which prevents having a broken code base while we do the refactor.
How to do it?
Imagine we have a class which has some public methods and they have similar signatures. This is the perfect case to apply the Parameter Object Refactoring.
Here are the steps on how to do it:
- Write unit tests if the class to refactor isn't tested yet :D
- Create a new immutable class to group the parameters of the method you want to refactor.
- Add a new parameter of this class to the method under refactor.
- In all the callers use
nullfor this parameter value.
- Run your tests.
- One by one, remove the old parameters from the signature of the method under refactor. Then in the method’s body you can use the new parameter object for the replaced value.
- Run your tests after each step.
If we do it right, then at the end of the refactor our tests should pass and the system should work as before. It is important to have in mind that we are only improving the design of the code, not changing its behaviour.
- Once you are done removing all the parameters you should think as to whether the behaviour you are executing can be moved to the new class!
Remember the Tell, don't ask principle:
"Object-orientation is about bundling together data and behaviour."
Why are you doing it?
Passing around the same group of parameters, like database query parts, is a code smell we call data clumps which can be seen in the book Refactoring by Martin Fowler.
These clumps of data should be grouped in a class because they lead to code duplication. Maybe not in the sense of duplicated methods but in the treatment we do to those parameters like validations, parsing, etc.
You can check out this nice list for more code smells like the one mentioned.
Need for a common language
Learning about refactoring techniques is very important for two reasons:
- It helps you improve the quality of existing code without breaking it. The key part is without breaking it.
- It sets a common language on how to improve code quality. This has the same benefit as Design Patterns as having a common language makes it much easier to discuss with colleagues in PRs or pairing sessions.
Show me how!
If you like this technique and you can't wait to jump in your code and refactor all the things I have one more piece of good news for you.
Android Studio (and of course IntelliJ) does this for you. For free. Gratis. Automatically.
So you don't need to remember all those steps. But it is always good to know what is going on under the hood, right? ;)