Me and one of my colleague were trying to solve the following problem:
Lets take an example of class TestClass One of my colleagues was facing problem of extracting one particular property from TestClass. Fetching one property from One particular class (in this case TestClass) is easy. but lets assume that you have multiple classes (TestClass1, TestClass2 ...) and you want to fetch one particular property from the collection of these classes with more and more reusability of code.
for example
public class A {
private String name;
.
.
.
}
List<String> listOfNames = createNameList(listOfAInstances);
createNameList() method would be like following:
List<String> tempList = new ArrayList<>();
for(A a : listOfAInstances) {
tempList.add(a.getName());
}
return tempList;
now if there are multiple classes I have to do this for each class and different properties.
I suggested two approaches:
- Reflection based approach.
- Create an interface called "PropertyExtractable" and put a method in it called "extractProperty" in it.
As shown below:
interface PropertyExtractable {
Object extractProperty();
}
public class A implements PropertyExtractable {
private String name;
.
.
.
public Object extractProperty() {
return this.name;
}
}
For this I can write some utility method which then can be used everywhere i.e.
public Object getPropertiesOfPropertyExtractable(PropertyExtractable prExtractable) {
return prExtractable.extractProperty();
}
This was the background, one other colleague of mine had different opinion about 2nd approach, he told me it seems like anti-pattern. He tried to explain to me but I didn't get it entirely so and hence I am asking here.
I am trying to compare this example with the Comparator interface in Java. Like java allows us to use Comparator on any of the custom object class and allows us to define the logic for comparison then why can't I define the logic for extraction
Further more interfaces can be used in this way, then why shouldn't we use it
I want to know is this approach an anti-pattern? why?
Aucun commentaire:
Enregistrer un commentaire