Consider the following analogy: If we have a class: "Car" we might expect it to have an instance of "Engine" in it. As in: "The car HAS-A engine". Similarly, in the "Engine" class we would expect an instance of "Starting System" or "Cooling System" which each have their appropriate sub-components.
By the nature of encapsulation, is it not true that the car "HAS-A" "radiator hose" in it as well as the engine?
Therefore, is it appropriate OO to do something like this:
public class Car {
private Engine _engine;
public Engine getEngine() {
return _engine;
}
// is it ok to use 'convenience' methods of inner classes?
// are the following 2 methods "wrong" from an OO point of view?
public RadiatorHose getRadiatorHose() {
return getCoolingSystem().getRadiatorHose();
}
public CoolingSystem getCoolingSystem() {
return _engine.getCoolingSystem();
}
}
public class Engine {
private CoolingSystem _coolingSystem;
public CoolingSystem getCoolingSystem() {
return _coolingSystem;
}
}
public class CoolingSystem {
private RadiatorHose _radiatorHose;
public RadiatorHose getRadiatorHose() {
return _radiatorHose;
}
}
public class RadiatorHose {//...
}
Here is a really good (and quite short) paper on the law of demeter called the The Paperboy, The Wallet, and The Law Of Demeter:
http://www.ccs.neu.edu/research/demeter/demeter-method/LawOfDemeter/paper-boy/demeter.pdf
When, you've read this you should read this short article which details how many people misinterpret the law of demeter. By doing this, the article acts as a really good explanation. It is aptly called "The Law of Demeter Is Not A Dot Counting Exercise"!!!!
http://haacked.com/archive/2009/07/14/law-of-demeter-dot-counting.aspx
Check up on the Law of Demeter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With