Skip to the workspace
Pebellslearn by building
Clean Code Principles  ›  Lesson

Keep Methods, Classes and Files Small

Keep methods / classes / files small 14 minSmall units that each do one job are easier to name, read, test and change, and refactoring in small steps keeps them that way.

software design architecture / Keep Methods, Classes and Files Small

Explore each scene at your own pace.

01 · The rule

The rule

Keep Methods, Classes and Files Small

Shelfwise's checkout function is 80 lines long. A bug report says receipts sometimes show the wrong total, and fixing it means scrolling past stock checks and card-charging code to find the three lines that matter. Big units hide things. Small units put each thing where you would look for it.

The rule

One job per unit; if describing it needs "and", split it.

A unit is a function, a class or a file. Each should do one job that you can name in a few words.

def checkout(cart, customer):
    ensure_in_stock(cart)
    total = price_cart(cart, customer)
    charge_card(customer, total)
    send_receipt(customer, cart, total)

This checkout is small because it only coordinates. The details live one level down, each in a function with a clear name. When the receipt total is wrong, you open price_cart and nothing else.

The same rule scales up. A class called OrderManager that prices, stores, emails and prints orders is four classes wearing one name. A 3,000-line file makes you search when you should be browsing. Group files by what they are about, such as orders/, payments/ and catalog/, so a newcomer can guess where a feature lives from the folder names alone.

Two companions keep units small over time:

  • Keep it simple. Prefer the plainest code that passes the tests. Clever code is hard to split, and hard to read.
  • Refactor often. Improve structure in small steps while you work in the code, with tests passing after each step. Leave each function a little tidier than you found it.
Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.