public House
{
WeatherStation station;
public float getTemp() {
//Law of Demeter has been violated here
return station.getThermometer().getTemperature();
}
}
public House
{
WeatherStation station;
public float getTemp() {
//Law of Demeter has been preserved?
Thermometer thermometer = station.getThermometer();
return getTempHelper(thermometer);
}
public float getTempHelper(Thermometer thermometer)
{
return thermometer.getTemperature();
}
}
In the code above you can see two different House class definitions. Both have getTemp() function, first of which violates Law of Demeter, but second one preservs it (according to Head First Design Patterns book).
The trouble is I don't quite get why second class preservs Law of Demeter, getTemp() function still has station.getThermometer() call, which (should?) violates Law of Demeter. "use only one dot" - I found this on wikipedia, which could be applicable, but I still need more detailed explanation - "In particular, an object should avoid invoking methods of a member object returned by another method" (wiki).
So could anyone explain why the second code example does not violates the law? What truly distinguishes second method from first one?