What is refactoring?
Refactoring is the process of rewriting parts of an application to leverage new components in the application architecture of the application environment. Refactoring is about improving the design of existing code. Improving, in this context, means to make more understandable and/or more flexible. Refactoring activities are typically about small steps, preferably reversible, for safety. This term can be confused with rearchitecting, but while refactoring is done at a keyboard, performed on real code, rearchitecting is most often done at a whiteboard or planning document.
Main refactoring techniques
- Red-green-refactor: One of the most widely used techniques for code refactoring is the red/green process used in agile test-driven development. With the red-green-refactor method, developers break refactoring down into three distinct steps: Stop and consider what needs to be developed [RED], then get the development to pass basic testing [GREEN], and finally, implement improvements [REFACTOR].
- Refactoring by abstraction: Branching by abstraction is a method used primarily when there is a large amount of refactoring to be done. Abstraction involves class inheritances, hierarchy, and extraction. The goal of abstraction is to reduce unnecessary duplications in software code.
- Composing method: Composing involves streamlining the code in order to reduce duplications. This is done through various processes, including extraction and inline methods.
- Extraction: This approach involves breaking down the code into smaller chunks to find and “extract” fragmentation. The fragmented code is then moved to a separate method and replaced with a call to this new method.
- Inline refactoring: This is a way to reduce the number of unnecessary methods while simplifying the code. By finding all calls to the method and replacing them with the content of the method, the method can then be deleted.
- Simplifying methods: The older code gets, the more garbled and complicated it tends to be. Consequently, it makes sense to go in and simplify a lot of the logic.
- Moving features between objects: This involves creating new classes and moving functionality between old and new classes. When one class has too much going on, it’s time to move some of that code to another class.
Refactoring examples
Examples of efforts than can be considered refactoring activities include:
- Breaking a large method into smaller, more focused methods
- Renaming variables and parameters to be more meaningful
- Moving a responsibility from one class to another (more appropriate) one
- Creating an interface, based on the methods in one class, then making that class implement the new interface.
Suggested Reading and Related Topics
- Cloud native services: Understand the type of services that are cloud-specific.
- Lift and shift and rearchitecting: Understand how refactoring differs from lift and shift and rearchitecting cloud migration options.