Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

This question has puzzled me for a while. A public property that can be accessed directly or a private property with getter? Which one is better/correct and why?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
576 views
Welcome To Ask or Share your Answers For Others

1 Answer

Exposing fields directly is considered a bad practice.

It is better to keep the field private and only expose the getter and setter. One advantage is that you can choose different access levels for the getter and setter, whereas a field has only a single access level. Another advantage of using getters is that it allows you to change the implementation without changing the class interface.

Even better is to avoid getters and setters where possible. Instead use methods that encapsulate a higher-level behaviour. This is because objects shouldn't be tampering with other objects' internal state (either via directly accessing fields, or indirectly via getters and setters).

Related


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...