What is the Rule of Thumb on Exposing Encapsulated Class Methods
- by javamonkey79
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 {//...
}