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?
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:
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()
andmap()
etc. were first prevalent in functional languages. Curiously this is actually more object-oriented too.