I have 2 classes as below ::
JavaScript
x
ItemA {
// varibales and methods.
}
ItemB{
// varibales and methods.
}
And I have a method in a service class :
JavaScript
public Map<String, ItemDetails> getItemDetails(Map<String, ItemA> itemMap, String itemType){
// do something
}
Now I need to pass ItemA or ItemB based upon some conditions in the caller. The return type doesn’t change in either case. How I can do that using generics or wild cards.
This is what I am trying to achieve :
JavaScript
public Map<String, ItemDetails> getItemDetails(Map<String, ?> itemMap, String itemType){
// do something
}
Is the above a good way to handle the scenario or please suggest a better approach. I am new to generics so need your kind help.
Advertisement
Answer
I think that a combination of Polymorphism and Generics could be the way to go.
Consider having an interface Item
and change your classes correspondingly
JavaScript
interface Item {
// TODO: declare methods common for all items
}
class ItemA implements Item {
// TODO: implement the interface
}
class ItemB implements Item {
// TODO: implement the interface
}
Then your method would become
JavaScript
public Map<String, ItemDetails> getItemDetails(Map<String, Item> items) {
// TODO: implement the method body
}
But beware writing conditions based on the class types, as it’s a common anti pattern
i.e. it’s better avoid code like this
JavaScript
// anti pattern, should be avoided
if (item instanceof ItemA) {
// do one thing
} else if (item instanceof ItemB) {
// do another thing
}