Just wondering what are your thoughts about these two different approaches: overloading methods vs. long/verbose method names.
Update: I am looking for a general pattern / best practice. The following is just an example.
Given an Organisation Structure with parent/child relationships
> OrgUnit
> - OrgUnit
> -- OrgUnit
> -- OrgUnit
two methods wich use the same code in great parts to get children for an xml element.
// 1) only 1 level down children
getSubOrgUnits()
// 2) all levels down
getSubOrgUnits(boolean includeChildren)
// 3) alternative naming of 1)
getDirectSubOrgUnits()
// 4) alternative naming of 2)
getAllSubOrgUnits()
So 1 and 2 is using parameters And 3 and 4 is using parameterless naming.
What would you go for and why? Also consider that 1) and 2) can get additional parameters which result in stuff like getChilds(true,false,null) but also 3) and 4) may get Names like getDirectSubUnitsExcludeSome()
Can be JAVA specific but a broader view on this is appreciated.
In my opinion, using verbose method name is a better solution.
But be careful, in some situation it's preferable to add some parameters
Example 1
private List<Element> getElementsByType(MyTypeEnum type);
public List<Element> getElementsOfType1();
public List<Element> getElementsOfType2();
public List<Element> getElementsOfType3();
/* VS */
public List<Element> getElementsByType(MyTypeEnum type);
Both implementations are good, it depends on you, on the size of MyTypeEnum
, on its capacity to increase in size. What do you want to expose ? Do you want the caller of getElements***
to be able to get all type of Element
?
Example 2
public void log(Level l, String s, Exception e);
/* VS */
public void logInfo(String s);
public void logWarning(String s);
public void logError(String s, Exception e);
In this case, the second part is better. Because it more readable, easy to understand on the first look. And because when you log in INFO
and WARNING
level, you don't need to specify an Exception
. So Specializing the method is a good thing. However, it's important to keep the method public void log(Level l, String s, Exception e);
public and not private because it could be useful to use this generic method in some cases.
Conclusion
It really depends on the situation but if you have the possibility to add specific methods, with verbose names, which specialize a target behavior, do it.
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