Decoupling


Introduction | Concepts of Decoupling | Law of Demeter | Class Exercise

Return To Home Page


Introduction

General Contractor and Subcontractors

You are building a new house.   You hire a general contractor to help you with all the work involved in the planning and building.   The general contractor does not do all the work personally.   Instead he hires subcontractors to do specific jobs.   One of them will work on the structural aspects of your new house, one will work on the electricity, one will implement the plumbing and so forth.   You do not have to worry about these subcontractors because the general contractor takes care of them.   It wouldn't make much sense if the general contractor got you all the subcontractors' phone numbers and had you deal with them all yourself.

This is the way your code should behave.   If we call on an object to perform a certain task for us, we want that object to take care of everything.   If the object directs us to a third-party object that we can receive the service from, it gets messy.   We don't want to deal with a third party when the object we called on can just as easily perform the service on our behalf.

The difference is how deeply our code is coupled.   If we don't have to deal with the third-party directly, then we are decoupling our code just as the general contractor helped us do with subcontractors.
Back to Top of Page

Concepts of Decoupling

Write shy code

Systems that do not practice decoupling are...

Systems that practice decoupling are...

In order to decide whether you should use decoupling...

Back to Top of Page

Law Of Demeter

Back to Top of Page

Class Exercise

For each of these exercises, determine if the method calls shown are acceptable according to the Law of Demeter.

Exercise 1

public void myGPA(studentRecord transcript) {
      Grades ave = transcript.getGPA();
      System.out.println(ave.printFormat( ));
}

Answer

Since transcript is passed in to the method, transcript.getGPA is a valid call.   We don't "own" ave since it was not passed into us.   Therefore ave.printFormat( )); is not a valid call.

In order to eliminate myGPA's coupling with Grades, we can use the following code:

void myGPA(studentRecord rec) {
      rec.printGPA( );
}

Exercise 2

public class Movers {
      private truck myTruck;
      private Vector myThings;

     public Movers( ) {
            myTruck = new truck( );
            myThings = new Vector( );
      }

      private void packTruck( );
            myTruck.addBelongings(myThings.elements( ));
      }
}

Answer

Since Movers owns myTruck and myThings, the calls to addBelongings and elements are both allowed.
Back to Top of Page