I am writing some immutable types in Java and wonder about how to name the accessor methods.
The Java Bean specification says that the names of accessors should be getX or isX, but since the fields are final, there is no setter and the fields are more like attributes than properties.
There for I'd prefer naming the getter methods like:
public T x()
public T getX()
Please note as an example:
public int java.lang.String#length()
(Which might have been specified so early in the Java history, so the conventions where not there yet.)
The immutable objects expose means to create modified versions of themselves through methods which I've tried to name like a verb rather than `MyObject MyObject#setX()`, this should limit the risk of the user calling setX() and think that the object has changed. So: `MyObject MyObject#shine(newShineLevel)`.
This is not always possible easy though. How would you name a method for adjusting an endpoint in a rectangle other than `Rectangle.setUpperLeft()`? `Rectangle.adjustUpperLeft` maybe, but now we're just moving away from the conventions.
I guess the question is relevant for all languages, but this questions concern Java in particular. Don't take classes in the Java API as an example of good practice. There are lots of inconsistencies in the Java API. For example for java.util.List the method is called size() instead of length(). Besides that, String is not really a Java bean so don't take it as an example for a Java bean.
以上就是Getters on an immutable type的详细内容，更多请关注web前端其它相关文章！