Method Code Smells and Refactorings
This is the second article from the First one
In the First article we talk about Statement code smells and refactorings in this we talk about Method Code Smells and Refactorings
Smell: Long Method(Bloater)
Prefer shorter methods to longer methods. Small methods can have better names because they are doing less, and since they can be well-named, are small, and don’t do much, they are easier than long methods to understand.
Methods should fit on one screen (no scrolling), Ideally fewer than 10 lines of code.
Refactoring Long Methods :
- Extract duplicated code into a new method
- Extract code into smaller methods
- Replace Conditional Logic with strategy
- Replace Nested Conditional With Guard Clause
- Compose Method
Extract duplicated code into a new method
Extract code into smaller methods
Replace Nested Conditional With Guard Clause
Compose Method
is nothing more than a method that calls out to other methods. It is best applied when all called methods have rawly the same level of detail.
Smell: Obscured Intent(Obfuscator)
Small and dense are not ends in and of themselves! Take the time to ensure your code is intention-revealing, not obscuring.
Smell: Conditional Complexity(Change Preventer)
Methods should limit the amount of conditional complexity they contain, The number of unique logical paths through a method can be measured as Cyclomatic complexity, which should be kept under 10.
Code metrics — Cyclomatic complexity — Visual Studio (Windows) | Microsoft Docs
Specific Method Refactorings
Inline Method
Introduce Explaining Variable
Declare a temp variable and set it to part of the complex expression, replace the result part of the expression with the temp.
Inline Temp
Confirm the temp variable is only assigned once,replace references to the temp with the right side of the temp’s assignment operation.
Replace Parameter with explicit methods
Create a separate, explicit method for each value of the parameter in the original method, move condition body logic to explicit methods and replace condition bodies with calls to new methods.
Later will discuss class-code-smells in another story.