8/20/2004

Method Overloading

There is a chance of surprise/confusion in using methods overloaded with subtype arguments (Effective java #26). e.g.

void foo(String s);
void foo(Long l);
void foo(Object o);
...
// in client code
Object x = "Some String";
foo(x); // call actually goes to foo(object).

Differenent method names instead of overloading is more elegant . e.g see below Bladestore interfaces to delete blades first one with overloaded and second one with different methods.
boolean delete(Blade blade);
boolean delete(long bladeID);
boolean delete(Blade[] blades);
boolean delete(String bladeName);

boolean delete(Blade blade);
boolean deleteById(long id);
boolean deleteByName(String name);
boolean deleteAll(Blade[] blades);

interface with different method names is better, It make intent absolutely clear.

Adding methods like is excess (overaction).

boolean deleteByName(char[] name);
boolean deleteById(Long l);

to second interface is an unnecessary(smelly) overloading. We are not adding any extra benefit.

Moral of the story : Overload only when method intent is absolutely same, method is useful and there is no possibility of confusion.

0 Comments:

Post a Comment

<< Home