Boxes: A Class on Paper

Code shows a design one line at a time, so teams draw it instead: each class as a box with its name, its fields and its methods, marked + for public and - for private, with an interface's box labeled as a promise.

Novice · Software Development · OOP · Updated

By

After this lesson you can

  • Read a class's box: its name, its fields and its methods, and whether each is public (+) or private (-)
  • Draw a class as a box from its code, and tell an interface's box from a class's

Key takeaways

  • A class diagram shows a design at a glance, before or after the code exists, and every pattern in this course comes with one.
  • A class's box has three parts: its name on top, its fields in the middle, its methods at the bottom.
  • A + in front of a member means public (any code may use it); a - means private (only the class itself may).
  • Fields are written name: type, and methods name(parameter: type): return type, such as price(hours: int): int.
  • An interface's box says «interface» above its name; an abstract class's name is in italics.

Before this: the bike-rental desk from The Object-Oriented Code You Need, and Interfaces: A Promise Any Class Can Keep.

Pedal & Go's rental desk works: bikes, e-bikes and scooters, each priced by the hour. Then Priya joins the team, opens the code and asks the question every new teammate asks: "What's in here, and how does it fit together?" You could walk her through it, file by file, line by line. Ten minutes in, she'll have seen a lot of lines and still not the shape. Code is read one line at a time; a design is a shape.

So teams draw it. By the end of this chapter you'll read and draw class diagrams, part of a drawing standard called UML (the Unified Modeling Language), and every pattern in this course comes with one. This lesson starts with the smallest piece: one class, drawn as a box.

One class, in code

Here is the desk's Bike class, with the lock every bike carries. Read it the slow way first, one line at a time:

Bike bike = new Bike("4821");
Console.WriteLine(quot;{bike.Name}: ${bike.Price(2)}");
Console.WriteLine(bike.Unlock("1234") ? "Open" : "Still locked");
Console.WriteLine(bike.Unlock("4821") ? "Open" : "Still locked");

class CodeLock
{
    private string code;

    public CodeLock(string code)
    {
        this.code = code;
    }

    public bool Open(string tried)
    {
        return tried == code;
    }
}

class Bike
{
    private CodeLock codeLock;

    public Bike(string lockCode)
    {
        codeLock = new CodeLock(lockCode);
    }

    public string Name => "Bike";

    public int Price(int hours)
    {
        return 10 * hours;
    }

    public bool Unlock(string code)
    {
        return codeLock.Open(code);
    }
}
Bike: $20
Still locked
Open
class CodeLock {
    private String code;

    CodeLock(String code) {
        this.code = code;
    }

    public boolean open(String tried) {
        return tried.equals(code);
    }
}

class Bike {
    private CodeLock lock;

    Bike(String lockCode) {
        lock = new CodeLock(lockCode);
    }

    public String name() {
        return "Bike";
    }

    public int price(int hours) {
        return 10 * hours;
    }

    public boolean unlock(String code) {
        return lock.open(code);
    }
}

void main() {
    Bike bike = new Bike("4821");
    IO.println(bike.name() + ": quot; + bike.price(2));
    IO.println(bike.unlock("1234") ? "Open" : "Still locked");
    IO.println(bike.unlock("4821") ? "Open" : "Still locked");
}
Bike: $20
Still locked
Open
class CodeLock:
    def __init__(self, code):
        self._code = code

    def open(self, tried):
        return tried == self._code


class Bike:
    name = "Bike"

    def __init__(self, lock_code):
        self._lock = CodeLock(lock_code)

    def price(self, hours):
        return 10 * hours

    def unlock(self, code):
        return self._lock.open(code)


bike = Bike("4821")
print(f"{bike.name}: ${bike.price(2)}")
print("Open" if bike.unlock("1234") else "Still locked")
print("Open" if bike.unlock("4821") else "Still locked")
Bike: $20
Still locked
Open
class CodeLock {
  #code;

  constructor(code) {
    this.#code = code;
  }

  open(tried) {
    return tried === this.#code;
  }
}

class Bike {
  name = "Bike";
  #lock;

  constructor(lockCode) {
    this.#lock = new CodeLock(lockCode);
  }

  price(hours) {
    return 10 * hours;
  }

  unlock(code) {
    return this.#lock.open(code);
  }
}

const bike = new Bike("4821");
console.log(`${bike.name}: ${bike.price(2)}`);
console.log(bike.unlock("1234") ? "Open" : "Still locked");
console.log(bike.unlock("4821") ? "Open" : "Still locked");
Bike: $20
Still locked
Open
class CodeLock {
  private code: string;

  constructor(code: string) {
    this.code = code;
  }

  open(tried: string): boolean {
    return tried === this.code;
  }
}

class Bike {
  name = "Bike";
  private lock: CodeLock;

  constructor(lockCode: string) {
    this.lock = new CodeLock(lockCode);
  }

  price(hours: number): number {
    return 10 * hours;
  }

  unlock(code: string): boolean {
    return this.lock.open(code);
  }
}

const bike = new Bike("4821");
console.log(`${bike.name}: ${bike.price(2)}`);
console.log(bike.unlock("1234") ? "Open" : "Still locked");
console.log(bike.unlock("4821") ? "Open" : "Still locked");
Bike: $20
Still locked
Open

Each language marks "private" its own way: C#, Java and TypeScript say private; JavaScript puts # in front of the name, and the language really does keep everyone else out; Python's leading underscore (_lock) is a polite sign that says "please don't touch", which nothing enforces. Two names had to change: in C#, lock is a keyword, so its field is called codeLock; in TypeScript, the browser's built-in types already declare a CodeLock, so its class is called CodeLock. Java has no properties, so its name is a method, name().

The same class as a box

A class diagram draws that class as a box in three parts, top to bottom:

  1. The name, in bold: Bike.
  2. The fields, the data each object keeps: name and lock.
  3. The methods, what you can ask it to do: price and unlock.

Bike drawn as a class box in three parts: its name; its fields, + name: string and - lock: CodeLock; and its methods, + price(hours: int): int and + unlock(code: string): bool. Labels say + means public, so any code may use it, and - means private, so only Bike may

Each line follows one small pattern, the same in every diagram:

  • A field is written name: type. - lock: CodeLock reads "a private field called lock, which holds a CodeLock."
  • A method is written name(parameter: type): return type. + price(hours: int): int reads "a public method called price: you hand it the hours, a whole number, and it hands back a whole number." A method that hands nothing back leaves off the last part.

The types are written in plain words (string, int, bool) rather than in any one language, so a C# team and a Python team read the same box.

Plus and minus: who may touch it

The mark in front of each line says who may use it:

Mark Read it as Means
+ "public" any code may use it
- "private" only the class itself may use it

The bike's lock is -, private. Nobody outside the bike can reach in and open it; they have to ask the bike, through + unlock, and the bike passes the code on. That's encapsulation: the data stays behind the object's own methods, so the object stays in charge of it. The box shows it at a glance, without reading a line of code.

Try it. Draw the CodeLock class as a box on paper. It has one private field and one public method. (Answer: CodeLock on top; - code: string in the middle; + open(tried: string): bool at the bottom.)

A promise's box: interfaces and abstract classes

Not every box is a class you can make objects from. The desk's Rentable is a promise that bikes, e-bikes and scooters keep: "I have a name, and I can price some hours." Its box has the word «interface» above the name. (The marks around it are called guillemets; on a whiteboard, <<interface>> is fine.)

Some designs keep a little shared code in an abstract class instead: a class that can't be made into an object by itself, only extended. Its name is written in italics, and so is any method it leaves for each kind to fill in.

Three kinds of box side by side: Rentable, marked «interface», a promise with no code of its own; Scooter, a class you can make objects from; and Vehicle, an abstract class with its name in italics, holding shared code and a part in italics for each kind to fill in

Italics are hard to see in a hand-drawn sketch, so you'll often see {abstract} written under the name too. Both mean the same.

How much goes in a box?

Only what helps the person reading it. A box drawn to explain the lock can leave out every other method. Constructors are usually left out, and so are the fields' starting values. A diagram is a conversation, not a copy of the code: the question is always "what does this reader need to see?"

Check yourself

2 questions to try on the lesson page.

So what

A box tells a teammate what a class keeps, what it does and what it hides, in the time it takes to look at it. Next, the arrows that join the boxes into a design.

Key terms

Cheat sheets