このブログについて
最近システム設計に興味を持ち、特にコード設計について学んだことをまとめます。
自分の今後の戒めも込めて。
クラス設計について
クラスを作るときは、そのクラス単体で正しく動くかを考えることが大切です。
悪いコード例
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は単体でテスト可能な構造になりました。
これが「クラス単位で正常に動作する設計」です。