What is so good about method overloading? While it’s nice in theory to have clean names, having many methods with the same name is a source for confusion. Method’s name is a great way to document its role and uniqueness. #dev #java

Follow

@orenh Good question triggering thoughts for me.

It can definitely be abused, but I'd say that the prime use case for method overloading is to make similar things work the same way, regardless of their strict type. That is, if what makes a Foobar object different from a Barfoo is not relevant to something they both can do or have done to them, why create methods like setValueForTypeFoobar(Foobar obj) and setValueForTypeBarfoo(Barfoo obj) which are essentially identical when you can create setValue(Foobar obj) and setValue(Barfoo obj)?

The other, related, use case is about focusing on the API contract and having things that are *conceptually* the same but *implementationally* different use the same name. Like having an add() method that when called like: int a = 3; a.add(4); will result in a being equal to 7, but when called like String a = "abc"; a.add("def"); will result in a being "abcdef".

In both cases, I think the emphasis is on the API contract, rather than the maintaining developer mental workload. It's probably a net win given examples like I've mentioned here, but I've definitely seen code in which people tried *way* too hard to make something use an existing method signature when they shouldn't have!

@pwinn super agree that if the difference is trivial it’s better to overload, and that for “external” APIs there is higher value for keeping API simpler and less divergent. Thanks for insightful points!

Sign in to participate in the conversation
CleverLibre Social

CleverLibre Social is an inclusive social instance for open discussion, learning, and community.
All cultures welcome.
Hate speech and harassment strictly forbidden.