开发者

When to use getX method

开发者 https://www.devze.com 2023-02-05 06:34 出处:网络
Coming from a C# background we use properties for something that would not take long to retrieve and a getX method if something would take long (msdn link). In Java, since there are no properties, do

Coming from a C# background we use properties for something that would not take long to retrieve and a getX method if something would take long (msdn link). In Java, since there are no properties, do you use getX for both cases or is there some other conventi开发者_StackOverflow中文版on to indicate a quick access from a not so quick access (other than documenting it)?

Edit: For example would you use a different naming convention for a time consuming get operation like database access or also use the getX naming convention?


Usually getX() methods are considered to be quick access methods and database-backed methods should be findX() or loadX() or something along those lines, but as far as I know there's no global agreement over it. Even the "getters should be quick" rule isn't adhered to sometimes.


The getX convention comes from JavaBean specification. More recently, usage of POJOs (Plain Old Java Objects) has become very popular since many frameworks manipulate your objects using getters and setters, including Spring and Hibernate.

More specifically:

  • getX for a nonboolean X (getter)
  • isX for a boolean X (getter)
  • setX for any value of X (setter)

If you won't use a framework that requires usage of POJOs, then by all means name your methods so you know what they do at first glance.


It depends on the situation and exactly what you're doing - for example, you might use loadX, fetchX, computeX - or sometimes just getX as for normal "cheap" properties.


As a rule of thumb, create a private member field for local access to your property and a getter / setter for external access.

Lots of 3rd party libs such as Spring rely on public methods for dependency injection (inversion of control), and and aspect oriented programming so using getter / setters facilitates that style of programming.

For example, Spring might be used to associate two objects together. Or you might use AOP to put some caching behaviour around a somewhat expensive get operation.

It also allows you to set breakpoints when the property is changed or retrieved, add logging etc. which can be useful for debugging.

0

精彩评论

暂无评论...
验证码 换一张
取 消