Should I always use getter/setter methods in Java classes or are there times when its okay to use public attributes?<>
This question already has an answer here:
- Why use getters and setters? 35 answers
Encapsulation is one of the core concepts of object oriented programming. Using getters and setters, is always, in my opinion good practice. One thing you should avoid is to have external entities mess with the internal structure of your class at will.
Typical example, consider having a dateOfBirth parameter. With a setter and getter you can have a small validation process, making sure that the user was not born in the future, or is impossibly old. You can also use the setter to update some other fields, such as age.
This minor validation can also enhance code re-usability since you do not need to have to make this check in any other class which invokes these getters and setters.