Which pattern has lower coupling in java: passing objects to a method or using composition?

950 Views Asked by At
//Ex1: (passing by object)
class A {
}

class B {
   void foo(A a) {
      <do something with a>
   }
}

//Ex2: (composition)
class C {
   A a
   void foo(){
      <do something with a>
   }
}

My question is: which pattern has lower coupling? And which pattern is more preferred in the real world ?

3

There are 3 best solutions below

0
On

I would say neither really has lower coupling, it's more implementation dependent. The best simple explanation of coupling, is that if the properties of class A change, how much will you need to change class B. In this case, the method foo will mostly likely have to make the same changes in both scenarios.

As for real world, it's completely dependent on the situation. Is class A only used in class B? Is it a web app, will you need to inject or outject class A? is class A going to be a singleton? What will be using class B? What does each class even do?!

In summary you can't make an argument either way until you look at the function of each class and how they will be used (that's where cohesion comes into it).

0
On

IMHO the second option (composition) is preferred, because:

  • The caller doesn't need to know about A
  • B is free to change its implementation to use a class other than A to do its job (without affecting/recompiling calling code)

The first option (passing by object) creates greater coupling between the caller and A (although B is coupled either way).

0
On

I will try to explain loose-coupling.

  1. Program in interface, that gives use the possibility of passing objects of different type which implements the same interface during runtime, and here classes from different inheritance tree can implement the same interface.

eg:

 Animal is the Interface

    Dog class implements Animal
    Cat class implements Animal
    Lion class implements Animal

   /////////////////
   calling method
  /////////////////

   callAnimal(new Dog);



  /////////////////
   called method
  /////////////////

  public void (Animal a){

   // some code

  }

Encapsulate the behaviour which keeps changing.... into Abstract classes, or Interfaces, so it will be easy when changes comes, and as it is loosely coupled, there are less chances for the code to break.