Micro refactoring that we forget so often
Introduction
Over time, the code becomes more complicated, more complicated. Graceful, in the old days, methods turn into "spaghetti" code of thousands of lines. Of course, up to a point it’s easier to just add a new condition or loop to the method. But when the number of lines in the method exceeds one hundred and at the same time it is a single block of conditions and cycles of incredible nesting, then it is much more difficult to understand it.
Problem
The method increases in size and its maintenance is much more complicated. Moreover, the structure of the method does not allow transparent refactoring without violating the logic of the code.
The code
We have a long code of the form:
public void process() {
if (condition1) {
...
if (condition2) {
...
for (condition3) {
...
if (condition4) {
...
}
}
} else if (condition5) {
...
} else if (condition6) {
...
}
} else {
...
}
}
This code cannot be maintained. Refactoring is difficult. It’s much easier to add another branch and forget. The level of nesting of structures is also high.
Refactoring
If in place of "..." there is a voluminous code, then the method can easily reach a size of several thousand lines. Two refactoring that correct the situation:
Method highlighting
We select large sections of code into separate methods. The complexity of the methods will be much lower. Do not be afraid that your methods are used in only one place. If someone needs a separate method in the future, then he will no longer duplicate the code or do complex refactoring, but simply use the necessary method.
Replacing nested conditional operators with a boundary operator
Behind the sophisticated name is a simple return. Here is the code after refactoring:
public void process() {
if (!condition1) {
...
return;
}
...
if (condition2) {
...
loopByCondition();
return;
}
if (condition5) {
...
return;
}
if (condition6) {
...
}
}
private void loopByCondition() {
for (condition3) {
...
if (condition4) {
...
}
}
}
As you can see, the code has become linear and simpler. Such code is much easier to maintain.
conclusions
These simple and understandable refactorings will make your code better. Do not forget about them. A more systematic refactoring is to read from Fowler. And modern IDEs allow you to do refactoring more comfortably in a few clicks.
The code specified in the last example can be written right away. It will be a more transparent, understandable and followed product. The main thing is to stick to the approach of writing linear code with little nesting. To do this, do not forget about the return statement and the ability to take out a complex block into a separate method.
Code in the style of a “stream of consciousness dump” should be disposed of immediately after creating the code at the stage of the review.