Overloading is fine. But if we consider that we have got two objects ObjectA and objectB. Both have got "id" and "name" variable. I would like to write a method (in third class), which returns the name of the given object. Writing overloaded function make me repeating the code. Is it a fine practice? Wouldn't be better to use generic functions instead?
So, I know I can write an overloaded function, sth. like that:
public String getInfo(ObjectA o){
if(o.getId()!=1) return o.name;
return "";
}
public String getInfo(ObjectB o){
if(o.getId()!=1) return o.name;
return "";
}
And it works fine. But both functions are identical! The only difference is the fact, they need an argument of the different type. Because they look the same, isn't it violating the DRY rule? I tried to write simple generic method, but IDE is marking that.getId and that.name() as an error and recommend casting it as ((ObjectA) that).getId() or ((ObjectB) that).getId(). Haven't I done it in the line" T that = clazz.cast(o);? What I am doing wrong?
public <T> String getInfo(Class<T> clazz, Object o) {
T that = clazz.cast(o);
if (that.getId()!=1) return that.name;
return "";
}
Generally I would like to know, if my idea is possible. How can i fix my error? And what is more, is it a good idea? Or is it better to simply write overloaded functions?
Both ideas are bad. Your ObjectA
and ObjectB
classes should implement a common interface that defines getId()
and getName()
methods.
Then you can get away with a single method:
public String getInfo(Interface o){
if(o.getId()!=1) return o.getName();
return "";
}
Your case is a good candidate for Programming to Interface. Create an interface and move common methods.
public String getInfo(InterfaceAB in){
if(in.getId()!=1) return in.getName();
return "";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With