Assuming that a A
class uses a B
class (directly or through a C
interface to decouple A
from C
).
Making it clear that A
and B
are independent parts, ie , the relationship between the two classes is not composition or an obvious aggregation, but there is a "weak" A
uses B
(in this case, through the contract established by C
).
Consider the two examples (in Java):
Example 1 - C as Instance Variable :
public class A {
private C c;
// Não estou discutindo injeção através de construtores vs. getters and setters
// Apenas assuma que 'c' foi inicializado de alguma maneira
public A(C c) {
this.c = c;
}
public metodo1() {
// faz algo com c
}
public metodo2() {
// faz algo com c
}
public metodo3() {
// não faz nada com c
}
}
Example 2 - C as parameter :
public class A {
public metodo1(C c) {
// faz algo com c
}
public metodo2(C c) {
// faz algo com c
}
public metodo3() {
// não faz nada com c
}
}
My question is what should I do with A
having an instance variable of type C
vs. when I should pass an instance of type C
as a parameter to the methods of A
?
In other words: In what situations would the API exposed in Example 1 be "better" than the API exposed in Example 2 and vice versa? What are the justifications for supporting this decision?
After many years as a developer I still make that decision on the basis of feeling . I also noticed that over time the construction of the 2 example (which was rare, and readily refactored for 1 in my code) began to become more acceptable and even preferable in most situations. However, until today I have difficulty formalizing the reasons that lead me to choose one building or another.