18 Mart 2019 Pazartesi

SOLID - Dependency Inversion Kuralı - Modüller Arasında Soyutlama Katmanı Olmalıdır

Giriş
Açıklaması şöyle.
The principle states that:

- High-level modules should not depend on low-level modules. Both should depend on abstractions.
- Abstractions should not depend on details. Details should depend on abstractions.
Şeklen şöyle

1. Dependency Inversion
Örnek
Elimizde şöyle bir kod olsun
public interface Keyboard { }

public class Windows98Machine {
  private final Keyboard keyboard;
  private final Monitor monitor;

  public Windows98Machine(Keyboard keyboard, Monitor monitor) {
    this.keyboard = keyboard;
    this.monitor = monitor;
  }
}
Böylece klavye ile bilgisayarı ayırabiliriz. Şöyle yaparız
public class StandardKeyboard implements Keyboard { }
2. Dependency Inversion ve Dependency Injection (Alt yapından gelir) Farklı Şeyler
Dependency Inversion ve Dependency Injection biraz farklı şeyler. Açıklaması şöyle
Dependency injection is one of the approaches to implement the Inversion of Control.

2.1 Dependency Injection
Artık bir çok alt yapı injection işini kolaylıkla yapıyor. Ancak bazen eski kodlarda Dependency Injection altyapısı olmadığı için, kodda Composer, Assembler gibi isimler sahip sınıflar görebiliriz.

Dependency Injection altyapısı olarak Spring, Jakarta CDI, Guice gibi şeyler kullanılabilir.

Dependency Injection Dikkatli Kullanılmalı
Açıklaması şöyle
Dependency Injection Problem
Dependency Injection on it's own can actually promote lower cohesion and higher coupling. Why, because Dependency Injection provides undisciplined short cuts to get references to objects. I need a repository to retrieve some data, I just inject it. I need some logic to work out some result, I just inject it. Overtime with on going improvements to systems, everything starts to reference everything else. Changing the interface of one thing becomes difficult, as so many things just pull it in (higher coupling). Furthermore, because it is so easy to "just inject" dependencies, convenience starts polluting single purpose logic of classes (lower cohesion).

Now, in disciplined development, we use principles such as SOLID to attempt to reduce this problem.




Hiç yorum yok:

Yorum Gönder