Let’s say you implement an interface like:
public interface Example {
InputStream getThatContent();
}
In this case there is no property, and the implementation may also have side effects (it can open a new InputStream).
This is happening also in other API, like JDBC:
public static Connection getConnection(String url,
String user,
String password)
throws SQLException
The method starts with get, and actually creates a new connection, so I’m wondering, is the getter/setter method naming convention valid only in POJO classes? Or in all Java classes?
12
The popular and accepted convention in the Java community about naming getters(1):
- When you want to expose private members and comply with encapsulation you should not make said members public but instead write setters and getters and that setters should be named
setX(Type value)
and getters should be namedType getX()
.
That’s all.
- The convention doesn’t prohibit non-getters from beginning with the prefix “get”.
- A method like
getFullName()
could returnfirstName+" "+LastName
even if that no class variable calledfullName
is part of the state. - The convention doesn’t state that methods beginning with the prefix “get” must not have side-effects. For example I could write to a log file inside a getter.
Clarifying what is a POJO and what’s not:
A class using java.util.Collection
continues to be a POJO because java.util.Collection
is part of JSE. A class is not a POJO when it uses JEE or some external framework or annotations.
(1) Meaning by getter a method that returns the value of a class’ private member.
- Is it a good idea to have a method like
getFullName()
when the class has nofullName
member?
IMO it is. Besides, there’s no way the consumer of a compiled class that has a getFullName()
method would know whether or not the class has a member called fullName
?
When I see the get prefix I take it to mean exposed state until the code proves otherwise. Whither that state is new or old doesn’t concern me.
If your building me something that is mine to own, hold, close, etc. then the name I expect is thingBuilder.
It’s impossible to tell you which is correct if you don’t tell me who owns the input stream. I’m saying if the caller is meant to own it use builder.
Otherwise use get to show you own this exposed state. This makes you a value object. Don’t use get if that’s not what you are.
2
It is a good idea when the external usage is similar to a getter. Two primary forms come to mind.
If the information that is being provided is rendered and not stored
Class Rectangle
{
int height = 3;
int length = 4;
getArea(){
return height * length;
}
getPerimeter(){
return 2 * ( height + length );
}
}
If the method is returning a new object from a factory class
Note: Apparently numbering a list breaks how code formatting works