When you have to access a “member variable”/field in a class, is it good practice to access it directly or call the getter and setter? and why?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
I see almost only benefits in making your fields private and only provide access through a getter and possibly a setter
PropertyChangeEventsfor bean properties, you can include this code in your setter. Otherwise all calls which modify this field directly should trigger a change event as wellsuper.setand do something extraThe only possible drawback I can think of is that it requires a bit more code to write (for the getters and setters), and a bit more code for accessing the field from outside the class. But with the current IDEs is this a pretty lame excuse
Some extra literature:
link1, link2