Refactoring process is very important and should not be underestimated by any software company.
Today i will try to extend my refactoring techniques knowledge and describe it here.
RED-GREEN REFACTORING
This is the most popular refactoring technique, used by many developers.
This is how the proccess looks like:
- at first we are writing failing test with the rules matching things we want to achieve
- second step is to writing the simpliest code we can which will pass the test (it will be green)
- last step is to improve the code with still keeping our test green
This process can be also called Test Driven Development.
REFACTORING BY ABSTRACTION
I am really big fan of this refactoring method. All articles in internet say that it is used mostly, when
we want to refactor big amount of code.
Examples of refactoring by abstraction:
- class inheritance
- creating new classes
- extraction of methods
- moving a code from a subclasses into a superclass to remove duplicates
COMPOSING METHOD
This is useful when we have very long methods in our code. For example Rubocop by default allows us to make
a method with maximum length of 16 lines. If our method is longer, we should use some of the refactoring techniques:
- extract method
- extract a variable
- remove assignments to paramters
SIMPLIFYING CONDITIONAL EXPRESSIONS REFACTORING
Conditional statements can become really complicated after time. This is how you can deal with this:
- replace nested conditional with guard clauses
- decompose conditional
- replace conditionals with polymorphism
SIMPLIFYING METHOD CALLS REFACTORING
In this example our goal is to make method calls simplier and easier to understand. Example:
- adding, removing, and introducing new parameters
MOVING FEATURES BETWEEN OBJECTS
This rule is about moving your code from one class to another. It will help you with reducing coupling and
for sure it will make the code simplier and more easy to read.
PREPARATORY REFACTORING
It is quite easy to imagine the situation where we need to add new feature, but the code we see is quite messy.
It won't allow us to make our changes in easy way.
Preparatory rule tells us that we should:
- make the code easier for our change
- implement our changes inside new created code
There is a really nice story told by Jessica Kerr in one of the ruby podcasts.
“It’s like I want to go 100 miles east but instead of just traipsing through the woods, I’m going to drive 20 miles north to the highway and then I’m going to go 100 miles east at three times the speed I could have if I just went straight there. When people are pushing you to just go straight there, sometimes you need to say, ‘Wait, I need to check the map and find the quickest route.’ The preparatory refactoring does that for me.”