Contents
Even if two functions perform the same process, separate them when their purposes differ. (2つの関数が同じ処理を実行する場合でも、目的が異なる場合は分離する)
解説
同じ処理内容であっても、目的やコンテキストが異なる場合は別々の関数として定義すべきです。これにより、将来的に要件が変わり処理内容が分岐した際に、影響範囲を限定できます。共通化を優先しすぎると、異なる目的の処理が密結合になり、一方の変更が他方に意図しない影響を与えるリスクが生じます。目的に応じた関数分離は、変更に強い設計の基本です。
具体例
// 悪い例(目的が異なるのに共通化)
func calculateDiscount(price float64) float64 {
return price * 0.9 // 10%割引
}
func processNewUserOrder(price float64) float64 {
return calculateDiscount(price) // 新規ユーザー割引
}
func processSeasonalSale(price float64) float64 {
return calculateDiscount(price) // シーズンセール割引
}
// 良い例(目的ごとに分離)
func calculateNewUserDiscount(price float64) float64 {
return price * 0.9 // 新規ユーザー割引
}
func calculateSeasonalDiscount(price float64) float64 {
return price * 0.9 // シーズンセール割引(将来変更可能性あり)
}
func processNewUserOrder(price float64) float64 {
return calculateNewUserDiscount(price)
}
func processSeasonalSale(price float64) float64 {
return calculateSeasonalDiscount(price)
}
