Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java method naming conventions and overloading [closed]

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?

like image 991
Pavel_K Avatar asked May 14 '16 09:05

Pavel_K


2 Answers

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.

like image 162
wero Avatar answered Sep 27 '22 16:09

wero


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.

like image 45
Monis Avatar answered Sep 27 '22 18:09

Monis