Reference · Desain

Prinsip SOLID di Product Catalog

Ringkasan satu halaman. Dari Lesson 0008.

Lima prinsip

PrinsipInti [2]ContohGejala pelanggaranPadanan Node/React
SRPSatu alasan untuk berubah; "alasan" = orang/peran yang memintaController / Service / RepositoryService yang juga export CSV + kirim email; constructor gemukRoute handler Express tipis
OCPTambah perilaku tanpa mengubah kode lamaIDiscountStrategy + PriceCalculatorswitch (customerType) yang terus bertambahObject map strategi
LSPPemakai interface tidak boleh dikejutkan implementasinyaIProductRepository SQL Server vs in-memoryNotImplementedException; exception di tempat kontrak mengembalikan nullFake repo Jest yang setia pada kontrak
ISPInterface sekecil kebutuhan konsumennyaIProductReader / IProductWriterInterface 15 method untuk konsumen yang butuh 1Pick<Store, "products"> untuk props
DIPBergantung ke arah abstraksi, bukan detailProductService(IProductRepository repo)new ProductRepository(...) di dalam ServiceProvider NestJS / createService(repo)

DIP dalam satu gambar

ProductService→IProductRepository←ProductRepository

Panah = dependency compile-time. Alur runtime tidak berubah: Service tetap memanggil Repository. [1] DIP = prinsip; Dependency Injection = teknik yang dimungkinkannya (container + constructor injection di Program.cs).

public class ProductService(IProductRepository repo) : IProductService { /* … */ }
builder.Services.AddScoped<IProductRepository, ProductRepository>();   // composition root
var sut = new ProductService(new Mock<IProductRepository>().Object);   // unit test

Jawaban 60 detik: "SOLID mana yang paling sering Anda terapkan?"

SRP dan DIP, karena keduanya membuat kode bisa di-unit-test. SRP: Controller hanya HTTP, Service aturan bisnis, Repository akses data; fitur baru seperti export CSV jadi class baru. DIP: Service bergantung pada IProductRepository, didaftarkan di Program.cs dan diinjeksi lewat constructor, sehingga di test saya memberi mock Moq (seperti jest.fn()). Gejala SRP dilanggar: constructor dengan terlalu banyak dependency.

Pertanyaan lanjutan yang mungkin muncul

Sumber: [1] Microsoft Learn: Architectural principles · [2] Robert C. Martin: Solid Relevance · [3] Dependency injection in ASP.NET Core