Tegu
Tegu

Reputation: 11

How Law of Demeter and Vector interacts?

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?

Upvotes: 1

Views: 63

Answers (1)

Robert Br&#228;utigam
Robert Br&#228;utigam

Reputation: 7744

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.

Upvotes: 1

Related Questions