Does a getter with a different return type qualify as a getter?

I have a variable named

List<String> names;

if i have a method like

Iterator getNames() { return names.iterator(); }

Is it technically a getter method because I changed it to an Iterator?


source to share

4 answers

Although the JDK allows this, it is not recommended to do so.

First, there are conventions based on the naming of your methods that have some dependencies on them.

I'm sure there are more dependencies, but even if they don't apply to your solution, it's still wise to follow the convention for the sake of readability. You don't want any other developer to curse you sometime in the future for breaking standards :)



I think this is a bad idea from a design point of view.

I would just get a getter public List<String> getNames()


For "safe publishing", you should consider returning a copy of the list in the implementation:

public List<String> getNames() {
    return new ArrayList<String>(names);




If your class will be introded with some bean tool, getNames () should return names. For clarity, call it what it is:





You are thinking about something else. The getXxx form method is a getter. Java conventions do not imply that you have to have a field named xxx. This is your business class, and encapsulation provides simple: the ability to hide your data structures to other classes.

Sorry for the typo, mobile.



All Articles