简体   繁体   中英

What should I use?

We have two different (maybe much more) ways to get an access to x variabel:

example.x and example.getX()

I think first is very fast, but we can't use that in some cases (for instance e.getX() when we handle window events).

The question is: should I use only example.getX() instead of example.x everywhere, or the combination of these ways is better?

It depends. It is considered good practice by most to use encapsulation in object oriented design. This means certain parts of the app only have access to the properties they need, and in very controlled ways--in this case, you would protect access and assignment by using getters and setters.

On the other hand, you could use dot access if you are setting a field in the same class, as long as you don't have a smart setter that does something important.

Note that in order for a class to be considered a Java Bean, it must have public setters/getters for every field (among other things). That is only applicable in Java, of course, so it's not really a reason when considering the question in a language agnostic context.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM