पाठ 23 / 25

Anti-Patterns and Code Smells

Recognise designs that make change painful.

Common traps

An anti-pattern is a common response to a problem that looks reasonable but usually backfires. A god object knows and does too much (a UserManager with 80 methods); split it by responsibility. Premature abstraction adds interfaces, factories and layers before there is variation to justify them, which is the most common way patterns themselves hurt. Golden hammer: applying a favourite pattern everywhere. Singleton abuse hides dependencies as global state. Anaemic domain model: objects with only getters and setters while all rules live in services (a debated point; it is fine for simple CRUD). Code smells are hints, not proofs: long methods, long parameter lists, feature envy (a method using another object's data more than its own), shotgun surgery (one change touches many files) and repeated switch statements on the same type code.

Smell to refactoring

A quick reference.

SMELL                                   POSSIBLE REMEDY
god object / huge class                 split by responsibility; facades per use case
same switch on a type code in 5 places  Strategy, polymorphism, or a lookup table
long parameter list                     parameter object or Builder
boolean flags tracking a lifecycle      State machine
deep inheritance tree                   composition, Strategy, Decorator
global singletons everywhere            dependency injection at the composition root
interface with one implementation       remove it until a second one is needed
vendor types across the codebase        Adapter / anti-corruption layer
shotgun surgery                         move related logic together

Kitchen gadgets

A kitchen full of single-purpose gadgets looks well equipped but slows cooking down. Good cooks keep a few versatile tools and buy a gadget only when a task keeps coming back.

त्वरित जाँच: Which is the best description of a god object?

  • A class that accumulates too many unrelated responsibilities
  • A class with exactly one method
  • An immutable value object
  • A small adapter around an SDK
Answer

A class that accumulates too many unrelated responsibilities — Split it by responsibility.