Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the Rule of Thumb on Exposing Encapsulated Class Methods

Tags:

oop

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 {//...
}
like image 857
javamonkey79 Avatar asked May 28 '10 23:05

javamonkey79


2 Answers

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

like image 191
Robben_Ford_Fan_boy Avatar answered Oct 28 '22 11:10

Robben_Ford_Fan_boy


Check up on the Law of Demeter.

like image 32
Jonathan Leffler Avatar answered Oct 28 '22 13:10

Jonathan Leffler