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, until a certain point, it is easier to simply add a new condition or cycle to the method. But when the number of lines in a method passes over a 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.
Problem
The method increases in size and its maintenance is much more complicated. At the same time, the structure of the method does not allow for transparent refactoring without violating the logic of the code.
Code
We have a long code like:
public void process() { if (condition1) { ... if (condition2) { ... for (condition3) { ... if (condition4) { ... } } } else if (condition5) { ... } else if (condition6) { ... } } else { ... } }
This code is impossible to accompany. Refactoring is difficult. It is much easier to add another branch and forget. The nesting level of structures is also high.
')
Refactoring
If there is a volumetric code in place of "...", then the method can easily reach a size of several thousand lines. Two refactoring to correct the situation:
Selection method
We allocate volumetric code sections into separate methods. The complexity of the methods will be much lower. Do not be afraid that your methods are used all in one place. If someone needs a separate method in the future, he will no longer duplicate code or do complex refactoring, but simply use the necessary method.
Replacing nested conditional operators with a boundary operator
Behind the tricky name is a simple return. Here is the code to get 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. This code is much easier to maintain.
findings
These simple and clear refactorings will make your code better. We should not forget about them. More systematically on refactorings worth reading with Fowler. And modern IDEs make refactoring more comfortable with just a few clicks.
The code specified in the last example can be written immediately. This will be a more transparent, understandable and accompanied product. The main thing is to follow the approach to write a linear code with a small nesting. To do this, do not forget about the operator return and the ability to make a complex block in a separate method.
It is necessary to get rid of the code in the
“dump of consciousness” style immediately after creation at the stage of review of the code.