Refactoring 101: Code Smells — Bloaters

Pavan Kumar S
TestVagrant
Published in
3 min readDec 14, 2021

Bad Code Smells are Symptoms of poor design or implementation choices — Martin Fowler

What is Code Smell?

A code smell is any character in the source code of a program that possibly indicates a deeper problem.

During the incremental development of any feature and refactoring the existing code we tend to miss out few coding standards and patterns which can be summarised in one line below.

“A Code Smell refers to functioning but poorly structured source code”

There are various frequently seen smells, let’s learn one of them which is known as “Bloaters”:

What are these Bloaters?

If you have methods and classes which have become huge over time and accumulated with a lot of features as the program evolves those are the Bloaters. In this blog, we are going to read one of the bloaters i.e “Long Methods”

Long Method: A method contains too many lines of code. Generally, any method longer than ten lines should make you start asking questions.

What happens if we have bloaters in code?

  • The longer a method or function is, the harder it becomes to understand and maintain it.
  • Long methods break the Single Responsibility Principle from SOLID and can result in code duplication

How to fix the Bloated Method?

As a rule of thumb, if you feel the need to comment on something inside a method, you should take this code and put it in a new method. Even a single line can and should be split off into a separate method if it requires explanations.

There are several ways of fixing the Bloated Method, different ways given with examples through which we can fix one of the code smells.

Note: In the given examples Code A is a code smell and Code B is refactored one.

  1. Extract Method: If a method performs multiple tasks, it should be extracted into the same or different classes based on SRP(Single Responsibility Principle )

Code A

Code B

2. Replace Temp with Query: Move the entire expression to a separate method and return the result from it. Query the method instead of using a variable. Incorporate the new method in other methods, if necessary.

Code A

Code B

3. Introduce Parameter Object: If your methods contain a repeating group of parameters. Replace parameters with an object.

Code A

Code B

4. Preserve Whole Object: Instead of getting several values from an object and then passing them as parameters to a method, pass the whole object.

Code A

Code B

5. Decompose Conditional: Decompose the complicated parts of the conditional into separate methods.

Code A

Code B

This article talks only about “Long Methods” keeping the readability as a key point, articles on other code smell types will be published soon.

Happy Reading….

--

--