Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it good practice to define a getter which does not return a specific field?

Tags:

java

getter

a kind of simple question. Are methods like this good practice?

private NavigableMap<Double, Site> m_sites;

private Site getRandomSite()
{
    return m_sites.ceilingEntry(Math.random()).getValue();
}

Or is it bad because it is a getter and you could expect that it would return the field "randomSite"?

like image 390
Stezy Avatar asked Oct 22 '25 05:10

Stezy


2 Answers

The method is fine, although I can understand that you wouldn't want to call it getRandomSite() because it looks like a getter method. Building on Gio's answer, I suggest you call the method fetchRandomSite() because as you said, this method does not generate the random site, it simply picks (or fetches) it out of a NavigableMap.

like image 189
CodeNewbie Avatar answered Oct 23 '25 21:10

CodeNewbie


If you, the author of the code, think it is confusing / bad with respect to the rest of your code base, than change the name to for example generateRandomNumber(). However, there is no convention which says that a "get method" must always return a field.

like image 36
Gio Avatar answered Oct 23 '25 20:10

Gio



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!