ファイル構成

1 件の記事

Contents

Even if a file exceeds 200 lines, do not place multiple classes (structs) in it. If you have multiple classes in a file over 200 lines, split them into separate files. (ファイルが200行を超えても、複数のクラス(構造体)を配置しない。200行を超えるファイルに複数のクラスがある場合は、別々のファイルに分割する)

解説

1ファイル1クラスの原則に従うことで、ファイルの責任が明確になり、目的のクラスを素早く見つけられます。複数のクラスが1ファイルにあると、ファイルが肥大化し、コードレビューやマージコンフリクトの解決が困難になります。特に200行を超える大きなファイルでは、クラスを分離することで可読性と保守性が大幅に向上します。ファイル名とクラス名を一致させることも推奨されます。

具体例

// 悪い例(1ファイルに複数のクラス)
// user_service.go (300行)
package service

type UserService struct {
    db Database
}

func (s *UserService) CreateUser(name string) error {
    // ... 100行の実装
}

type OrderService struct {
    db Database
}

func (s *OrderService) CreateOrder(items []Item) error {
    // ... 100行の実装
}

type PaymentService struct {
    gateway PaymentGateway
}

func (s *PaymentService) ProcessPayment(amount float64) error {
    // ... 100行の実装
}

// 良い例(クラスごとに分離)
// user_service.go (100行)
package service

type UserService struct {
    db Database
}

func (s *UserService) CreateUser(name string) error {
    // ... 実装
}

// order_service.go (100行)
package service

type OrderService struct {
    db Database
}

func (s *OrderService) CreateOrder(items []Item) error {
    // ... 実装
}

// payment_service.go (100行)
package service

type PaymentService struct {
    gateway PaymentGateway
}

func (s *PaymentService) ProcessPayment(amount float64) error {
    // ... 実装
}

参考リンク