Method Overloading – Should Overloaded Methods Be Renamed?

designmethod-overloadingnamingreadability

Assume an interface containing these methods :

Car find(long id);

List<Car> find(String model);

Is it better to rename them like this?

Car findById(long id);

List findByModel(String model);

Indeed, any developer who use this API won't need to look at the interface for knowing possible arguments of initial find() methods.

So my question is more general :
What is the benefit of using overloaded methods in code since it reduce readability?

Best Answer

This is a relatively minor issue compared to many other bad readability practices you could be susceptible to, so I'd say it's mostly a matter of taste how you name your methods.

With that said, if you are going to do something about it, I would follow this practice:

  • Overload if...

    The methods obey nearly the same contract but simply operate on different input (imagine a phone operator who can look up your account by your personal tax ID number, your account number, or your name and birthday). This includes returning the same type of output.

  • Use a different name if...

    The methods do substantially different things or return different output (like your case). You might consider using a different name if one accesses the database and one does not.

    In addition, if the type returned is different, I would also change the verb to indicate that:

    Car findById(long id);
    
    List findAllByModel(String model);
    
Related Topic