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