LetmeKnow
LetmeKnow

Reputation: 13

Observer Pattern and Dependency Inversion

I have a controller class that implements Observer and another use-case class (called UseCase) (which is on a lower clean architecture layer) that extends Observable.

If my controller stores an instance of UseCase and calls useCase.addObserver(this), is this breaking clean architecture, or is this an example of dependency inversion?

Upvotes: 1

Views: 737

Answers (1)

Mark Seemann
Mark Seemann

Reputation: 233135

The Dependency Inversion Principle (DIP) is a design-time principle. Briefly stated:

Abstractions should not depend on details. Details (concrete implementations) should depend on abstractions

If the Controller in question depends on Observable and we assume that Observable is an interface or base class defined on the same level of abstraction (or higher) as the Controller, then the Controller depends on an abstraction.

If I understand the OP correctly, the UseCase class depends on the abstraction (Observable) because it extends it.

This all fits the DIP.

The fact that at run time an Observable instance like UseCase gets composed with the Controller doesn't change things. Due to polymorphism, the Controller doesn't depend on UseCase.

The assumption, however, is that some third party is responsible for composing the Controller with the UseCase instance. If the Controller news up the UseCase instance itself, then the DIP is violated because the Controller would depend on an implementation detail (the UseCase class).

Additionally, if the Controller stores an instance of UseCase instead of Observer, then, again, the DIP is violated.

Upvotes: 1

Related Questions