Long Method
Long Methods
Those are methods that contains a significant amount of code. There’s no rule for this smell, how long? 10, 20, 30 lines? Each case must be analyzed in its context.
It’s important that the method follows the Single Responsibility Principal, here’s a great video from Uncle Bob Martin about Solid Principles
which covers SRP
.
If we want to reduce the length of a method body
Extract Method
Suppose we have this code:
|
|
We can extract the address details into a new method.
|
|
Here we separated a piece of code to a new function and replaced the old code with a call to the method. Also, we removed the unecessary comment, since the function name is meaningful.
If we want to reduce local varibles and parameters before extracting a method
Replace Temp with Query
Sometimes, we have code that is not easily extracted, it depends on variables. Such as:
|
|
We can replace the canGetDiscount
variable with a new function.
|
|
Introduce Parameter Object
If we got methods with too many arguments, we can replace them with objects.
|
|
|
|
Instead receiving two parameters, we now receive an object with the data we need.
Preserve Whole Object
Similarly, we can preserve the whole object and not create variables to hold data.
|
|
|
|
We can replace a method with Method Object
Replace Method with Method Object
If we have many local variables and they are tightly coupled and we can’t apply Extract Method
, we can try Replace Method with Method Object
.
|
|
|
|
If we have conditionals and loops
Decompose Conditional
Complex conditions can be decomposed into methods.
|
|
|
|
The method checkClientVIPLevel()
would be responsible to check VIP Level of a client.
Extract Method
We can use Extract Method
to handle loops.
|
|
|
|
Payoff
- Classes with short methods live longer among all types of object-oriented code. The longer the code, the harder it becomes to understand and maintain it
- Long code are great place to hide bugs and duplicated code, and we don’t want that, let’s keep the code as short as possible
Performance
- The impact of additional code is not worth to worry about, it’s probably not even noticed significantly
- With cleaner and understandable code, it’s easier to find non-performatic code and then apply performance techniques