How Law of Demeter and Vector interacts?

74 Views Asked by At

So i have this code:

Public class Worker{
   private String gender;
   ...
   public Boolean isMale(){
      return gender=="Male";
   }
}

Public class Business{
   private Vector<Worker> vWorkers;
   ...
   public void showMaleWorkers(){
      for(Integer I=0; I<vWorkers.size();I++){
         if(vWorkers.elementAt(I).isMale()){
         ...
         }
      }
   }
}

Is the "if" breaking the law of demeter and if yes how could I solve it?

1

There are 1 best solutions below

2
On

It does. Both technically and conceptually.

It's not your code though. The culprit is the Vector which gives out internal state, instead of thinking ahead and implementing behavior.

The behavior in the vector's domain that it should implement for us would be "iterating" and "filtering". Something like this:

public void showMaleWorkers() {
   vWorkers
      .filter(_.isMale())
      .forEach(...);
}

This does not violate LoD while doing the exact same thing. At no point are we calling methods on things that we don't have access to directly. This is sometimes called "functional style", because filter() and map() etc. were first prevalent in functional languages. Curiously this is actually more object-oriented too.