ドメイン

1 件の記事

Contents

Keep domain responsibilities out of utility packages. (ドメインの責務をユーティリティパッケージに入れない)

解説

ユーティリティパッケージは、文字列操作や日付計算など、ドメイン非依存の汎用的な機能を提供すべきです。ドメイン固有のビジネスロジックをユーティリティに配置すると、ドメイン層の概念が分散し、ビジネスロジックの理解が困難になります。ドメインロジックは、適切なエンティティやドメインサービスに配置することで、コードの意図が明確になり、保守性が向上します。

具体例

// 悪い例(ドメインロジックがutilに配置)
package util

func CalculateOrderTotal(items []Item) float64 {
    total := 0.0
    for _, item := range items {
        total += item.Price * float64(item.Quantity)
    }
    // 1万円以上で送料無料(ドメインルール)
    if total < 10000 {
        total += 500  // 送料
    }
    return total
}

// 良い例(ドメインロジックはドメイン層に配置)
package domain

type Order struct {
    items []Item
}

func (o *Order) CalculateTotal() float64 {
    subtotal := 0.0
    for _, item := range o.items {
        subtotal += item.Price * float64(item.Quantity)
    }

    shippingFee := o.calculateShippingFee(subtotal)
    return subtotal + shippingFee
}

func (o *Order) calculateShippingFee(subtotal float64) float64 {
    const freeShippingThreshold = 10000
    const standardShippingFee = 500

    if subtotal >= freeShippingThreshold {
        return 0
    }
    return standardShippingFee
}

// utilパッケージは汎用機能のみ
package util

func FormatCurrency(amount float64) string {
    return fmt.Sprintf("¥%.0f", amount)
}

参考リンク