Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I always use getter/setter methods in Java classes or are there times when its okay to use public attributes? [duplicate]

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?

like image 355
ChrisMcJava Avatar asked Dec 01 '22 18:12

ChrisMcJava


1 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.

like image 172
npinti Avatar answered Dec 10 '22 13:12

npinti