What is the thumb rule for exposing encapsulated class methods

Consider the following analogy: If we have a class: “Car”, we can expect that it will have a copy of “Engine”. Like in: "HAS-A car engine." Similarly, in the Engine class, we expect an instance of the Start System or Cooling System, each of which has corresponding subcomponents.

By the nature of the encapsulation, isn't it true that it has a “HAS-A” radiator hose and also an engine?

So is OO appropriate 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 {//...
}
+5
source share
4 answers

Check out the Law of Demeter .

+4

, . , , , , .
, . , , . , .

+2

, , , . , . , "" "", " " "", , . ( OO, UML.)

In fact, I do not see the wrong code in the code. I am not a car, so I may be wrong in understanding the system. But if the engine of a real car needs a cooling system, I think you are doing it right. Yes, the engine class does call a property of the cooling system class, but since the engine uses the public method to call the cooling system, this is the right way. Again, I do not know the real car system, so I could be wrong in this particular project.

0
source

All Articles