Code bloater refers to code that is unnecessarily large and hard to work with. Bloaters can be blocks of code, methods, and classes that have increased to such large and complex proportions. Code bloaters occur due to different reasons that will be part of this discussion. If we don’t resolve or eliminate the code bloaters, they accumulate over time as the program evolves. Let’s discuss the code bloaters and see how to eliminate them from the code.
> Long Method > Large Class > Primitive Obsession > Long Parameter List > Data Clumps
Long method
When a method contains a different type of operation and has grown excessively large, that is considered a long method. A “long method” code smell is an anti-pattern that refers to a method, that has grown excessively complex. Due to less readability and maintainability, it’s considered a poor practice.
How to identify?
When a method contains more than 10 lines, you should start asking questions.
What reason for the problem?
Imagine the method is like a room and people keep putting their stuff into the room, but they never take anything out. So, over time, the room becomes messy. As putting the stuff in the room is easy but cleaning it up or removing things feels harder.
The same problem occurs in code because people often find it easier to write the code in an existing method rather than creating a new method for them. The problem starts when a developer thinks “It’s just a couple of lines, why make a whole new method for that?” This code smell remains unnoticed until it turns into a big mess.
How to resolve the bloater long method?
Whenever you feel you have to make a comment on something inside a method, you should take that code and put it in a new method. If any code line or code block requires explanation, then split off into a separate method. Keep a descriptive method name so nobody needs to look at the code to see what it does.
You have to do refactoring to eliminate this code smell. Here are the refactoring techniques.