I have been coding Java for about 4 months. I just started coding android games with the guide of an intro book. In the book, they do not encapsulate any attributes of classes.
Ex.
public class GameObject{
public Vector position;
public float angle;
public GameObject(float angle, Vector position){
...
I was always told that encapsulation of attributes was good practice: only allow access to the private attributes through getter and setter methods.
Could any programmers with more experience than me tell me which way is the "proper" coding way of creating attributes? And of course why please?
And then a follow up: should I always encapsulate private attributes of a class and provide getter and setter methods, or are there situations where public attributes are okay?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With