0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

コード設計学習6 クラス単位で正常に動作するように設計する

Posted at

このブログについて

最近システム設計に興味を持ち、特にコード設計について学んだことをまとめます。
自分の今後の戒めも込めて。

クラス設計について

クラスを作るときは、そのクラス単体で正しく動くかを考えることが大切です。

悪いコード例

class Order
{
    public int ProductId;
    public int Quantity;

    public int GetTotalPrice()
    {
        var price = new ProductService().GetPrice(ProductId);
        return price * Quantity;
    }
}
Console.WriteLine("完了しました。");

Orderが内部でProductServiceを直接生成しており、依存関係が固定されています。
これではテスト時にサービスを差し替えられず、単体で動作確認ができません。

良いコード例

class Order
{
    private readonly IProductRepository _productRepository;

    public int ProductId { get; }
    public int Quantity { get; }

    public Order(int productId, int quantity, IProductRepository productRepository)
    {
        ProductId = productId;
        Quantity = quantity;
        _productRepository = productRepository;
    }

    public int GetTotalPrice()
    {
        var product = _productRepository.Find(ProductId);
        return product.Price * Quantity;
    }
}

依存を外部注入(DI)に変えることで、Orderは単体でテスト可能な構造になりました。
これが「クラス単位で正常に動作する設計」です。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?