AlgoViz

OOP anti-patterns

medium 50 min

An anti-pattern is a common answer that looks helpful and costs more than it gives: the god object, spaghetti code, copy and paste, the golden hammer, cargo cult and early optimization.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 4:28

OOP anti-patterns

1:04Reel

Theory

Read or listen first. About 2 min.

What it is

An anti-pattern is a repeated answer to a repeated problem that seems good at first and makes things worse later. The seems good part matters: nobody chooses a god object. It grows, one convenient method at a time.

A code smell is smaller: a sign at the surface, such as a long method, that hints at a deeper problem. A smell is a reason to look. It is not a proof, and a number such as 20 lines is a hint and not a law.

Each anti-pattern has an opposite that is just as bad. The opposite of a god object is a swarm of tiny classes that do nothing alone. The opposite of copy and paste is one function with nine flags. Good design lies between, and the reasons decide where.

Why it exists

A name makes a talk short. God object says in two words: too many reasons to change, everyone edits it, nobody can test it.

Knowing the first signs is cheaper than a repair. A class with 12 methods in three groups can be split in an hour, one with 120 in weeks.

In interviews you will produce some of them under time pressure, most often a GameManager that does everything. Seeing it yourself and saying how you would split it earns more than never having had it.

A short history

  1. 1974

    Donald Knuth warns in a paper on structured programming that premature optimization causes trouble. In the same text Knuth asks to not pass up the important few percent, found by measuring.

  2. 1974

    Richard Feynman describes cargo cult science: copying the form of a thing without what makes it work. Programmers later borrowed the name.

  3. 1995

    Andrew Koenig coins the word anti-pattern, inspired by the book Design Patterns.

  4. 1997

    Brian Foote and Joseph Yoder publish Big Ball of Mud, about systems without a clear structure and why they are so common.

  5. 1998

    Brown, Malveau, McCormick and Mowbray publish the book AntiPatterns with many of the names used today.

  6. 1999

    Martin Fowler's Refactoring makes code smells known, a term by Kent Beck, and pairs each with a repair.

Words to know

God object
One class that knows and does too much. Also called god class or blob.
Spaghetti code
Control flow so tangled that a path cannot be followed.
Big ball of mud
The same at the level of a whole system: no visible structure.
Cargo cult
Using a form without knowing what it is for.
Golden hammer
One favourite tool for every problem.
Lava flow
Dead code that nobody dares to remove.
Feature envy
A method that uses the data of another class more than its own.
Shotgun surgery
One change needs small edits in many classes.
Anemic model
Classes with data and no behaviour, next to services with behaviour and no data.
Wrong abstraction
Code shared because it looked alike, not because it means the same.
Extract class
The repair that moves a group of fields and their methods into a new class.

The solution, twice

Reach the regular design first. Then go where a FAANG interviewer digs.

How it works

Step through the idea, or press Play.

Step 1 of 4

Notice. A smell at the surface

Understand it

Start here

The trunk in the attic

Max has one large trunk in the attic. When something has no place, it goes into the trunk. That is quick, every time.

Max and the trunk

Nobody plans the trunk. It wins each single day and loses the year.

The big six

Anti-patterns you will meet

  • God object

    One class does everything. Many reasons to change, hard to test, all teams edit it. Repair: extract focused classes such as UserService, OrderService, PaymentService.

  • Spaghetti code

    Deep nesting, global state, jumps between everything. Repair: small functions, early returns, layers that call downwards only.

  • Cargo cult

    A factory for a class with one implementation, because patterns are good. Repair: ask what it is for. Plain new is fine.

  • Premature optimization

    A custom data structure for ten items. Repair: plain list first, measure, then improve what the profiler shows.

  • Copy and paste

    The same 20 lines in ten files, and a bug fixed in nine. Repair: one function with a name, if the copies mean the same. See DRY.

  • Golden hammer

    Inheritance for every relation, a singleton for every service. Repair: know several tools. See inheritance or composition.

Their tempting reason, and the opposite mistake

Anti-patternWhy it temptsOpposite mistake
God objectEverything is at handForty classes with one line each
SpaghettiQuick to add a branchSeven layers that only forward
Cargo cultLooks professionalRefusing every pattern
Premature optimizationFeels cleverIgnoring an obvious n squared on a million rows
Copy and pasteDone in a minuteOne function with nine flags
Golden hammerWe know it wellA new tool for each task

The bad shape: one class, all arrows

AppManager- users, orders, mails- cache, log, config+ createUser()+ sendEmail()+ processPayment()+ generateReport()+ validateInput()+ 45 more

1/3One class in the middle

50 methods, many fields. Any method may touch any field.

uses

The good shape: one job per class

Outbox+ send(to, text)

1/3The smallest part first

Sending was used by all and needs nothing. It is extracted first.

uses

One reason to change each: see single responsibility.

Small signs

Six smells and their usual repair

SmellHintRepair
Long methodOver about 20 lines, or a comment before each partExtract method, named after the comment
Long parameter listMore than three, or several of one type in a rowParameter object
Duplicate codeBlocks that change togetherExtract function or class
Dead codeCannot be reached, or has no callersDelete it. Version control remembers
Magic number* 1.08 + 5.99Named constants with a unit
Feature envyReads the fields of another class more than its ownMove the method to the data
The numbers start a talk. A 30 line method that reads like a list can be fine.
Python
class Customer:    def __init__(self, years, cents, level): self.years, self.cents, self.level = years, cents, levelclass Order:    def __init__(self, base, customer): self.base, self.customer = base, customer    def total(self):                              # envy, nesting, magic numbers        c, d = self.customer, 5        if c.years > 5:            if c.cents > 1000000:                if c.level == "gold":                    d = 20        return self.base * (100 - d) // 100 + 599LOYAL_YEARS, LOYAL_CENTS = 5, 1_000_000LOYAL_PERCENT, USUAL_PERCENT = 20, 5SHIPPING_CENTS = 599class BetterCustomer(Customer):    def discount_percent(self):        loyal = self.years > LOYAL_YEARS and self.cents > LOYAL_CENTS and self.level == "gold"        return LOYAL_PERCENT if loyal else USUAL_PERCENTclass BetterOrder(Order):    def total(self):        return self.base * (100 - self.customer.discount_percent()) // 100 + SHIPPING_CENTSfor who in [(6, 1_000_001, "gold"), (6, 1_000_001, "silver"), (1, 0, "gold")]:    print(Order(10_000, Customer(*who)).total(), BetterOrder(10_000, BetterCustomer(*who)).total())
Three smells in one method, then repaired. The discount moved to the class that owns the data.
Edit and run it in your browser
Java
// beforevoid createUser(String firstName, String lastName, String email, String phone,                String street, String city, String state, String zip, String country) { }// afterrecord Name(String first, String last) {}record Contact(String email, String phone) {    Contact { if (!email.contains("@")) throw new IllegalArgumentException("email"); }}record Address(String street, String city, String state, String zip, String country) {}record CreateUser(Name name, Contact contact, Address address) {}void createUser(CreateUser request) { }
A long list of texts in a row: two can be swapped and the compiler is silent. Parameter objects give the parts types.
TypeScript
// beforefunction processOrder(id: string) {  getOrder(id, (order: any) => {    validate(order, (ok: any) => {      if (ok) pay(order, (payment: any) => { confirm(order, payment, () => { /* and deeper */ }); });    });  });}// afterinterface Item { value: string }const values = (data: { items: Item[] }): string[] => data.items.map((i) => i.value);async function processOrder(id: string): Promise<void> {  const order = await getOrder(id);  await validate(order);  const payment = await pay(order);  await confirm(order, payment);}
Two smells of TypeScript: nested callbacks and any. The second version reads from top to bottom, and the compiler checks it.
C++
// beforeclass ResourceManager {    Database* db;    Connection* conn;public:    ~ResourceManager() { delete db; delete conn; }   // and the copy constructor?};// after: no destructor neededclass ResourceManager {    std::unique_ptr<Database> db;          // one owner    std::shared_ptr<Connection> conn;      // shared owner, only if it truly is shared};constexpr double Pi = std::numbers::pi;    // not 3.14159 here and 3.1416 theredouble area(double radius) { return Pi * radius * radius; }
Raw owning pointers: who deletes? A copy of the manager deletes twice. Smart pointers write the owner into the type.

Judgement

Smell or fine?

Should I repair it now?

Ugly code that nobody touches costs nothing today.

Two classes hold the same ten lines of email checking. What do you do?

BreaksA base class for both
How
class UserAndOrderBase with checkEmail.
Limit
Two classes are now related for ever because of a helper. The next helper goes there as well.
Choose when
Never for a helper.
WorksLeave both
How
Wait for a third copy.
Limit
A fix must be made twice.
Choose when
You are not sure that they mean the same.
StrongA small value class
How
Email checks itself when it is made. Both classes take an Email.
Limit
Callers change from text to Email.
Choose when
Both copies state the same rule of the business.

Quick rules that help

  • More than one reason to change? Split
  • The same rule in three places? Extract
  • A number without a name? Name it
  • Want to optimize? Measure first
  • Ten collaborators? Look for two classes
  • No callers? Delete

Rules that hurt when blindly used

  • No method over 20 lines, ever
  • An interface for every class
  • Never copy two lines
  • Never use a switch
  • Every service is a singleton
  • Comments are always a smell

Summary

The whole topic in one minute.

An anti-pattern seems helpful and costs later. Name it, name its cost, and repair in small steps under tests.

God object: find groups of methods that use the same fields, and extract the smallest group first. Keep the old name as a thin front until callers have moved.

Beware of the opposite: tiny classes without a job, abstractions with flags, patterns without a reason. Duplication is cheaper than a wrong abstraction.

  • Anti-pattern: seems helpful, costs later. Smell: a sign at the surface.
  • The big six: god object, spaghetti, cargo cult, premature optimization, copy and paste, golden hammer.
  • Each has an opposite that is just as bad.
  • Find groups by shared fields, extract the smallest first, keep an old front.
  • Duplication is cheaper than the wrong abstraction.
  • Repair what hinders the next change, under tests, in its own commit.

Sources