Method Code Smells and Refactorings

Amr elshaer
3 min readMay 14, 2022

--

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

Refactoring the Long Method code smell | MAKOLYTE

Extract code into smaller methods

Refactoring the Long Method code smell | MAKOLYTE

Replace Nested Conditional With Guard Clause

before
after

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.

before
after

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.

before
after

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.

Steve smith image

Code metrics — Cyclomatic complexity — Visual Studio (Windows) | Microsoft Docs

Specific Method Refactorings

Inline Method

before
after

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.

before
after

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.

Before
After

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.

before
after

Later will discuss class-code-smells in another story.

--

--

Amr elshaer
Amr elshaer

Written by Amr elshaer

Software engineer | .Net ,C# ,Angular, Javascript

Responses (4)