I have a service which must return person by some properties. And I see two strategies for naming these methods:
The first one:
getPersonById(int id)
getPersonByBirthDate(Date date)
getPersonByBirthDateAndSex(Date date,Sex sex)
getPersonByNameAndSex(String name,Sex sex)
getPersonByBirthDateAndNameAndSex(Date date,String name,Sex sex)
etc..
or applying overloading rules do the following:
getPerson(int id)
getPerson(Date date)
getPerson(Date date,Sex sex)
getPerson(String name,Sex sex)
getPerson(Date date,String name,Sex sex)
Which is right according to java naming convention?
Independent of the overloading question your design suffers from combinatorial API explosion: You start to introduce methods for all possible combinations of search criterions. An alternative would be to introduce a builder which collects criterions and in the end returns the person.
Example:
queryPerson().byId(5).run();
queryPerson().byName("John").bySex(Sex.MALE).run();
queryPerson().bySex(Sex.FEMALE).run();
And the service API now only has a nice queryPerson()
method.
Overloading is always better. Many java-based KNOWN frameworks follow this approach. Also, the main concept of overloading is because of condition you mentioned.
Having overloaded methods simplifies the developer's readability as no separate names have to be remembered. Also, eclipse's Ctrl + Space feature would always suggest which method one wants to use.
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