OOP Anti-Patterns

The design mistakes interviewers plant in code review questions, how to name each one, and the refactoring that fixes it.

Overview

An anti-pattern is a design that looks reasonable, gets used again and again, and reliably makes code harder to change. Most of the ones in this topic are code smells: surface signs that a deeper design problem is near. Kent Beck coined the term 'code smell' while helping Martin Fowler with *Refactoring* (1999; second edition 2018), and that book's smell catalog is where most of these names come from.

Interviewers use anti-patterns in two ways. In a code review question they hand you a class and ask what is wrong with it. In a design question they watch whether your own design drifts into one. In both cases the score comes from naming the problem precisely, saying why it hurts, and showing the fix.

A field guide

Ten anti-patterns cover most of what you will be shown. For each, here is what it looks like and the fix.

  • God class: one class that knows about everything and does most of the work. Extract classes, one responsibility each.
  • Anemic domain model: objects are only fields, getters and setters, and all the rules sit in service classes. Move the rules into the objects that own the data.
  • Primitive obsession: money as a float, an email as a string, an id as an int, validated in many places. Write a small value object per concept.
  • Feature envy: a method reads another object's fields more than its own. Move the method to the object it envies.
  • Data clumps: the same three fields travel together everywhere. Group them into one object.
  • Switch on type: if kind == 'circle' ... elif kind == 'square' repeated in several places. Use polymorphism: one class per kind, one method each.
  • Shotgun surgery: one small change touches ten classes. Bring the scattered code together.
  • Long parameter list: a method with eight arguments. Pass an object, or split the method.
  • Refused bequest: a subclass overrides inherited methods to do nothing. Use composition instead of inheritance.
  • Global state: singletons and static fields read from anywhere. Pass dependencies in.

Interview questions

  • What is a god class, and how do you refactor one?
  • What is an anemic domain model, and how do you make it rich?
  • What is primitive obsession, and what does the fix look like?
  • What is feature envy, and where should the method go?
  • Why is a switch on a type field a smell, and what replaces it?
  • How do you refactor safely when the anti-pattern is in code with many callers and few tests?

Sign up free to read the full topic

More Low-Level Design topics

Start free on Cariara · Coding problems · System design studio