4️⃣

[読書メモ]オブジェクト設計スタイルガイド 4章2~4節 with TypeScript

2024/02/14に公開

オブジェクト設計スタイルガイドを読みながら、TypeScriptでやるならどうやるかを考えながら書きました。
要約的に読める内容になっていると思うので、サクッと3分ぐらいで読める記事となっています。
https://www.oreilly.co.jp/books/9784814400331/

4.2 バリューオブジェクト:置き換え可能、匿名、イミュータブル

識別できる必要はなく、他の値に変更したければ、新しいオブジェクトを返すのが良い
-> 事実上イミュータブルに。

class Quantity {
  private constructor(private quantity: number, private scale: number) {}

  static fromInt(quantity: number, scale: number) {
    return new Quantity(quantity, scale)
  }

  add(other:Quantity) {
    if (other.scale !== this.scale) {
      return
    }

    return new Quantity(this.quantity + other.quantity, this.scale)
  }
}

4.3 データ転送オブジェクト:設計のルールの少ないシンプルなオブジェクト

DTO:データ転送オブジェクト
基本的にイミュータブルにする必要もなく、あまりルールは必要ない。振る舞いも持たない。

4.4 イミュータブルオブジェクトを優先する

ミュータブルなオブジェクトだと変更後の状態を理解するために時間かかっちゃうよね。という話。

class Year {
  constructor(private year: number) {}

  next() {
    return new Year(this.year + 1)
  }
}

let year = new Year(2020)
year.next() // 何の影響もない

year = year.next() // 戻り値を取得する

Discussion