INDEX
はじめに
![](https://techlog.site/wp-content/uploads/2024/02/nwe_icon.jpeg)
現場で役立つシステム設計の原則 / 変更を楽で安全にするオブジェクト指向の実践技法 を読みました。
個人的に覚えたい内容を記録します。
1. 小さくまとめてわかりやすくする
わかりやすい名前を使う
let basePrice: number = a * b;
let basePrice: number = qty * up;
let basePrice: number = quantity * unitPrice;
目的ごとに変数を用意する
let price: number = quantity * unitPrice;
if (price > 1000)
price += 500;
price = price * taxRate();
let basePrice: number = quantity * unitPrice;
let shippingConst: number = 0;
if (basePrice > 1000)
shippingConst = 500;
let shippingCost: number = (basePrice * shippingConst) * taxRate();
メソッドとして独立する
let basePrice: number = quantity * unitPrice;
let shippingConst: number = 0;
if (basePrice > 1000)
shippingConst = 500;
let shippingCost: number = (basePrice * shippingConst) * taxRate();
let basePrice: number = quantity * unitPrice;
let shippingConst: number = getShippingConst(basePrice);
let itemPrice: number = (basePrice * shippingConst) * taxRate();
値の範囲を制限してプログラムを分かりやすく安全にする
const addNumbers = (num1: number, num2: number): number => num1 + num2
enum Number1To5 {
One = 1,
Two,
Three,
Four,
Five
}
const addNumbers = (num1: Number1To5, num2: Number1To5): number => num1 + num2
複雑さを閉じ込める
場合分けのロジックを整理する
なるべくelseを使わない
if (isChild()) {
return 0;
} else if (isSenior()) {
return 1;
} else {
return 2;
}
if (isChild()) return 0
if (isSenior()) return 1
return 2
業務ロジックを分かりやすく整理する
メソッドをロジックの置き場にする
class Person {
private firstName: string;
private lastName: string;
constructor(firstName: string, lastName: string) {
this.firstName = firstName;
this.lastName = lastName;
}
getFirstName(): string {
return this.firstName;
}
getLastName(): string {
return this.lastName;
}
}
class PersonName {
private firstName: string;
private lastName: string;
constructor(firstName: string, lastName: string) {
this.firstName = firstName;
this.lastName = lastName;
}
getFirstName(): string {
return this.firstName;
}
getLastName(): string {
return this.lastName;
}
getFullName(): string {
return this.lastName + this.firstName;
}
}