Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

//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 ?


1 Answers

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.

like image 96
Kumar Vivek Mitra Avatar answered Feb 03 '26 20:02

Kumar Vivek Mitra



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!