← Back to Week 5

Week 5 Cheat Sheet

Quick reference for OOP concepts — classes, getters, JUnit, static, has-a relationships.

Thinking in Objects

Class Anatomy (Review)

public class Person {
    // fields (data) — private
    private String name;
    private int age;

    // constructor
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    // getters / setters
    public String getName() { return name; }
    public void setName(String n) { this.name = n; }
}

Getter Conventions

// stored
public String getName() { return name; }

// derived (no fullName field)
public String getFullName() {
    return firstName + " " + lastName;
}

// boolean
public boolean isAdult() { return age >= 18; }

Access Modifiers

Best practice: always write the access modifier explicitly. Don't rely on the package-private default — it makes intent unclear.

Method Overloading

public Hotel(String n, int s, int r) { ... }
public Hotel(String n, int s, int r,
              int bs, int br) { ... }

Cohesion & Coupling

Anti-pattern: a class that knows about three unrelated things (payroll + dinner + weather) has low cohesion. Split it.

JUnit Testing

Test naming — 3 underscored parts
// methodUnderTest_StateUnderTest_ExpectedBehavior
checkIn_RoomInitialStatus_RoomIsOccupiedAndDirty
checkout_RoomIsOccupied_RoomIsNotOccupied
punchOut_HoursNotSet_HoursWorkedSetCorrectly
Other styles exist (e.g. shouldX_whenY). Pick one for your project — and stick with it.
Arrange / Act / Assert
@Test
public void checkIn_RoomInitialStatus_RoomIsOccupiedAndDirty() {
    // Arrange
    Room room = new Room(2, 100.0);

    // Act
    room.checkIn();

    // Assert
    assertTrue(room.isOccupied());
    assertTrue(room.isDirty());
}
Common Assertions
assertEquals(expected, actual) assertNotEquals(expected, actual) assertTrue(boolean) assertFalse(boolean) assertArrayEquals(expected, actual)

Static Members

private static double // shared
        interestRate;
private double balance;     // per instance

BankAccount.setInterestRate(0.045);  // no instance needed

Has-A Relationships

public class Hand {
    private ArrayList<Card> cards;
    public void deal(Card card) {
        cards.add(card);
    }
}

The Testing Pyramid

Unit (most)
A single method on a single class. Milliseconds. Hundreds.
Integration
Two or more classes (or class + file/db) working together. Seconds. Dozens.
End-to-End (few)
Full user flows through the whole system. Minutes. Few.
Glossary →