Getters on an immutable type

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() rather than 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前端其它相关文章!

赞(0) 打赏
未经允许不得转载:web前端首页 » JavaScript 答疑

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

前端开发相关广告投放 更专业 更精准