[General boards] [Winter 2019 courses] [Fall 2018 courses] [Summer 2018 courses] [Older or newer terms]

Dependency Inversion design pattern


#1

Are there any tips for detecting the violation/use of dependency inversion pattern when given some code?


#2

You mean dependency inversion solid principle or dependency injection design pattern?


#3

Oh I got it mixed up. I mean the dependency inversion principle for D in SOLID.


#4

If there is any type checking involved e.g. recall from FishTank,

              if (FishTank.myLittleFishies[a][b] instanceof Fish) {
                  ((Fish) FishTank.myLittleFishies[a][b]).draw(g);
              }else if (FishTank.myLittleFishies[a][b] instanceof Seaweed) {
                ((Seaweed) FishTank.myLittleFishies[a][b]).draw(g);
              }else if (FishTank.myLittleFishies[a][b] instanceof HungryFish) {
                ((HungryFish) FishTank.myLittleFishies[a][b]).draw(g);
              }if (FishTank.myLittleFishies[a][b] instanceof Bubble) {
                  ((Bubble) FishTank.myLittleFishies[a][b]).draw(g);
              }

#5

That’s right. In this example, the code calls the draw method for each type. So it shouldn’t matter what type you have. Instead, we could depend on FishTankEntity instead of its subclasses.

If adding a subclass means adding another case or an overloaded method, then Dependency Inversion is being violated.

Another exmaple is:
public void updateBalance(Account a) with dependency inversion.

Compare that to:
public void updateBalance(SavingsAccount a)
public void updateBalance(CheckingAccount a)
public void updateBalance(LineOrCredit a)
etc.