Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using generic methods as an alternative to overloading?

Tags:

java

oop

generics

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?

like image 648
Thamiar Avatar asked Aug 21 '15 12:08

Thamiar


2 Answers

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 "";
}
like image 66
Kayaman Avatar answered Nov 15 '22 19:11

Kayaman


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 "";
}
like image 39
Suresh Atta Avatar answered Nov 15 '22 18:11

Suresh Atta