AlgoViz

Ensuring proper encapsulation

medium 40 min

Private fields are the start, not the end.

Watch lesson4:46

Employee and Meeting, sealed

Read it, run it, change a line and run it again.

Loading editor…

Try to break an invariant from the last lines only. If you manage without touching an underscore, you found a door.

The same in Java
import java.time.LocalDate;import java.util.*;record Raise(int percent, long before, long after) {}final class Employee {    private static final int MAX_RAISE = 50;    private final String name;    private long salaryCents;    private final LocalDate hired;    private final List<String> skills = new ArrayList<>();    private final List<Raise> raises = new ArrayList<>();    Employee(String name, long salaryCents, LocalDate hired) {        if (name == null || name.isBlank()) throw new IllegalArgumentException("name is required");        if (salaryCents < 0) throw new IllegalArgumentException("salary cannot be negative");        this.name = name.strip();        this.salaryCents = salaryCents;        this.hired = Objects.requireNonNull(hired);    }    String name() { return name; }    long salaryCents() { return salaryCents; }    LocalDate hired() { return hired; }              // cannot change, no copy needed    List<String> skills() { return List.copyOf(skills); }    List<Raise> raises() { return List.copyOf(raises); }    boolean hasSkill(String s) { return skills.contains(s.strip().toLowerCase(Locale.ROOT)); }    void addSkill(String skill) {        String clean = skill.strip().toLowerCase(Locale.ROOT);        if (clean.isEmpty()) throw new IllegalArgumentException("skill is empty");        if (!skills.contains(clean)) skills.add(clean);    }    void giveRaise(int percent) {        if (percent < 0 || percent > MAX_RAISE)            throw new IllegalArgumentException("raise must be 0 to " + MAX_RAISE + " percent");        long before = salaryCents;        long after = Math.multiplyExact(before, 100L + percent) / 100;        raises.add(new Raise(percent, before, after));        salaryCents = after;    }}final class Meeting {    private Date start;    private Date end;    private final List<String> guests;    Meeting(Date start, Date end, List<String> guests) {        Date s = new Date(start.getTime());     // copy first        Date e = new Date(end.getTime());        List<String> people = List.copyOf(guests);        if (!s.before(e)) throw new IllegalArgumentException("start must be before end");        if (people.isEmpty()) throw new IllegalArgumentException("a meeting needs a guest");        this.start = s;                         // keep what was checked        this.end = e;        this.guests = people;    }    Date start() { return new Date(start.getTime()); }    Date end() { return new Date(end.getTime()); }    List<String> guests() { return guests; }    // already unmodifiable    void moveTo(Date start, Date end) {        Date s = new Date(start.getTime());        Date e = new Date(end.getTime());        if (!s.before(e)) throw new IllegalArgumentException("start must be before end");        this.start = s;        this.end = e;    }}class Main {    public static void main(String[] args) {        Employee e = new Employee(" Alice ", 7_500_000, LocalDate.of(2024, 3, 1));        e.addSkill("Python");        e.giveRaise(10);        Date start = new Date(9), end = new Date(10);        Meeting m = new Meeting(start, end, List.of("lee"));        end.setTime(0);        System.out.println(e.salaryCents() + " " + e.skills() + " " + m.end().getTime());    }}
The same in C++
#include <algorithm>#include <cctype>#include <iostream>#include <stdexcept>#include <string>#include <vector>struct Raise { int percent; long long before; long long after; };inline std::string tidy(std::string s) {    auto space = [](unsigned char c) { return std::isspace(c) != 0; };    s.erase(s.begin(), std::find_if_not(s.begin(), s.end(), space));    s.erase(std::find_if_not(s.rbegin(), s.rend(), space).base(), s.end());    return s;}class Employee {public:    static constexpr int kMaxRaise = 50;    Employee(std::string name, long long salaryCents, int hiredYear)        : name_(tidy(std::move(name))), salaryCents_(salaryCents), hiredYear_(hiredYear) {        if (name_.empty()) throw std::invalid_argument("name is required");        if (salaryCents_ < 0) throw std::invalid_argument("salary cannot be negative");    }    const std::string& name() const { return name_; }          // read only, do not keep it longer than the object    long long salaryCents() const { return salaryCents_; }    int hiredYear() const { return hiredYear_; }    std::vector<std::string> skills() const { return skills_; }  // by value: a copy    std::vector<Raise> raises() const { return raises_; }    bool hasSkill(const std::string& s) const {        return std::find(skills_.begin(), skills_.end(), lower(s)) != skills_.end();    }    void addSkill(const std::string& skill) {        auto clean = lower(skill);        if (clean.empty()) throw std::invalid_argument("skill is empty");        if (!hasSkill(clean)) skills_.push_back(clean);    }    void giveRaise(int percent) {        if (percent < 0 || percent > kMaxRaise) throw std::invalid_argument("raise out of range");        const long long after = salaryCents_ * (100 + percent) / 100;        raises_.push_back({percent, salaryCents_, after});        salaryCents_ = after;    }private:    static std::string lower(const std::string& s) {        auto out = tidy(s);        std::transform(out.begin(), out.end(), out.begin(), [](unsigned char c) { return std::tolower(c); });        return out;    }    std::string name_;    long long salaryCents_;    int hiredYear_;    std::vector<std::string> skills_;    std::vector<Raise> raises_;};struct Slot { int start; int end; };class Meeting {public:    Meeting(Slot slot, std::vector<std::string> guests)      // by value: already copies        : slot_(slot), guests_(std::move(guests)) {        if (slot_.start >= slot_.end) throw std::invalid_argument("start must be before end");        if (guests_.empty()) throw std::invalid_argument("a meeting needs a guest");    }    Slot slot() const { return slot_; }    std::vector<std::string> guests() const { return guests_; }    void moveTo(Slot slot) {        if (slot.start >= slot.end) throw std::invalid_argument("start must be before end");        slot_ = slot;    }private:    Slot slot_;    std::vector<std::string> guests_;};int main() {    Employee e(" Alice ", 7500000, 2024);    e.addSkill("C++");    e.giveRaise(10);    auto skills = e.skills();    skills.clear();                       // only the copy    Slot s{9, 10};    Meeting m(s, {"lee"});    s.end = 0;    std::cout << e.salaryCents() << " " << e.skills().size() << " " << m.slot().end << "\n";}
The same in TypeScript
interface Raise {  readonly percent: number;  readonly before: number;  readonly after: number;}class Employee {  static readonly MAX_RAISE = 50;  readonly #name: string;  #salaryCents: number;  readonly #hired: Date;  readonly #skills: string[] = [];  readonly #raises: Raise[] = [];  constructor(name: string, salaryCents: number, hired: Date) {    if (!name.trim()) throw new Error("name is required");    if (!Number.isSafeInteger(salaryCents) || salaryCents < 0) throw new Error("salary must be whole cents, 0 or more");    this.#name = name.trim();    this.#salaryCents = salaryCents;    this.#hired = new Date(hired.getTime()); // Date can be changed: keep our own  }  get name(): string { return this.#name; }  get salaryCents(): number { return this.#salaryCents; }  get hired(): Date { return new Date(this.#hired.getTime()); }  get skills(): readonly string[] { return [...this.#skills]; }  get raises(): readonly Raise[] { return [...this.#raises]; }  hasSkill(s: string): boolean { return this.#skills.includes(s.trim().toLowerCase()); }  addSkill(skill: string): void {    const clean = skill.trim().toLowerCase();    if (!clean) throw new Error("skill is empty");    if (!this.#skills.includes(clean)) this.#skills.push(clean);  }  giveRaise(percent: number): void {    if (!Number.isInteger(percent) || percent < 0 || percent > Employee.MAX_RAISE)      throw new Error(`raise must be 0 to ${Employee.MAX_RAISE} percent`);    const before = this.#salaryCents;    const after = Math.floor((before * (100 + percent)) / 100);    this.#raises.push(Object.freeze({ percent, before, after }));    this.#salaryCents = after;  }}class Meeting {  #start: Date;  #end: Date;  readonly #guests: readonly string[];  constructor(start: Date, end: Date, guests: readonly string[]) {    const s = new Date(start.getTime());    const e = new Date(end.getTime());    const people = [...guests];    if (!(s < e)) throw new Error("start must be before end"); // also refuses an invalid Date    if (people.length === 0) throw new Error("a meeting needs a guest");    this.#start = s;    this.#end = e;    this.#guests = people;  }  get start(): Date { return new Date(this.#start.getTime()); }  get end(): Date { return new Date(this.#end.getTime()); }  get guests(): readonly string[] { return [...this.#guests]; }  moveTo(start: Date, end: Date): void {    const s = new Date(start.getTime());    const e = new Date(end.getTime());    if (!(s < e)) throw new Error("start must be before end");    this.#start = s;    this.#end = e;  }}const e = new Employee(" Alice ", 7_500_000, new Date(0));e.addSkill("TypeScript");e.giveRaise(10);const end = new Date(10);const m = new Meeting(new Date(9), end, ["lee"]);end.setTime(0);console.log(e.salaryCents, e.skills, m.end.getTime());