CodePark/ questions / OOP principles & composition
START PRACTICINGPRACTICE
Backend question · Software design & patterns › OOP principles & composition

This class has private fields and getters/setters. Is it encapsulated? How would you improve it?

class Subscription {
  private status: "active" | "cancelled" = "active";
  private cancelledAt?: Date;
  getStatus() { return this.status; }
  setStatus(s: "active" | "cancelled") { this.status = s; }
  setCancelledAt(d: Date) { this.cancelledAt = d; }
}

Not really. Private fields with one setter for each field only hide the syntax of field access. The object still cannot protect its own rules. For example, any caller can:

  • set status to cancelled without setting cancelledAt
  • cancel the subscription twice

Encapsulation means the object owns its invariants (rules that must always be true). Replace the setters with methods that show the intention. Example: a cancel(now: Date) method. It throws an error if the subscription is already cancelled. Otherwise it sets both fields together.

Keep read access (getters) where callers really need it. But expose operations that match business actions, not raw state changes.

The result:

  • Every valid state change lives in one place.
  • You test the rule once.
  • Callers cannot leave the object half-updated.
  • Getters and setters for every field are not real encapsulation.
  • The object should protect its own rules (invariants).
  • Replace setters with business operations like cancel().
  • Fields that change together are updated in one method.