Reputation: 707
Is it a good practice to pass a strategy instance (an interface implementation) to a method so that the method can return objects of a specific type based on the strategy instance type?
For example,
I have a method getData(String x, String y)
but this needs to return objects of either type A
or type B
. Most of the stuff in this method is common and hence i'm thinking of reusing a single method.
I'm thinking of passing an extra parameter TypeInterface t
and check type of this instance in the method and build objects of either A
or B
.
Upvotes: 0
Views: 80
Reputation: 131326
Most of the stuff in this method is common and hence i'm thinking of reusing a single method.
You will make the client API more verbose and complex by introducing an additional parameter that besides is a class.
As alternative you could declare two distinct public methods with a difference in their naming and in their implementation you could rely on a common private method for the common processings.
For example :
Suppose X
the interface that A
and B
implement.
public X getA(String x, String y){
X a = new A();
// specificities for A ...
...
// common processing
commonForGet(a);
return a;
}
public X getB(String x, String y){
X b = new B();
// specificities for B ...
...
// common processing
commonForGet(b);
return b;
}
private void commonForGet(X x){
...
}
Upvotes: 2