関数のパラメータは5つ以内にする
Contents
A function should have no more than five parameters. More than five suggests too many responsibilities or insufficient aggregation. (関数のパラメータは5つ以内にすべき。5つを超える場合は、責任が多すぎるか、集約が不足していることを示す)
解説
パラメータが多い関数は、理解と使用が困難であり、単一責任原則に違反している可能性が高いです。パラメータが5つを超える場合、関連するパラメータをオブジェクトにまとめるか、関数の責任を分割すべきです。パラメータを集約することで、関連する値が明確になり、関数シグネチャがシンプルになります。これにより、コードの可読性と保守性が向上します。
具体例
// 悪い例(パラメータが多すぎる)
func CreateUser(
firstName string,
lastName string,
email string,
phone string,
address string,
city string,
zipCode string,
country string,
) error {
// パラメータの順序を覚えるのが困難
// ...
}
func main() {
CreateUser("John", "Doe", "john@example.com", "123-456",
"123 Main St", "Tokyo", "100-0001", "Japan")
}
// 良い例(パラメータをオブジェクトに集約)
type UserProfile struct {
FirstName string
LastName string
Email string
Phone string
}
type Address struct {
Street string
City string
ZipCode string
Country string
}
func CreateUser(profile UserProfile, address Address) error {
// 関連するデータがグループ化され、理解しやすい
// ...
}
func main() {
profile := UserProfile{
FirstName: "John",
LastName: "Doe",
Email: "john@example.com",
Phone: "123-456",
}
address := Address{
Street: "123 Main St",
City: "Tokyo",
ZipCode: "100-0001",
Country: "Japan",
}
CreateUser(profile, address)
}
// さらに良い例(責任を分割)
func CreateUser(profile UserProfile) (UserID, error) {
// ユーザー作成のみに集中
// ...
}
func SetUserAddress(userID UserID, address Address) error {
// 住所設定を別関数に分離
// ...
}
参考リンク
関数のパラメータは5つ以内にする https://www.tricrow.com/core/coding-standard/max-five-parameters.html

