-1

Everybody says that we need to make every variable in class private and access to them with getters/setters. I'm trying to understand why we always need to do this? For example, if I make a simple game and create an Object class, which stores x and y coordinates of any object and other objects (e.g. sprites), isn't it better to do:

public class Object
{
    public float x, y;

    public Object(float x, float y)
    {
        this.x = x;
        this.y = y;
    }
}

public class Sprite extends Object
{
    public Sprite(float x, float y, /* other stuff, e.g. img src */)
    {
        //...
    }
}

and use it like:

sprite1 = new Sprite(/* ... */);
checkSomething(sprite1.x, sprite1.y);

Isn't it more natural and faster? Like if we need to compare objects coordinates thousands times in one frame? We don't need to validate coordinates - every float is okay. So why complicate it with functions like getX() and setX(/* ... */) doing the same thing?

  • 2
    If the location of the object in your example was `final` (never again to change once set) then it's reasonable to offer it as `public`. That is the same as `array.length` for example. Changing the state directly can have unintended consequences in the larger code. – ChiefTwoPencils Oct 18 '15 at 01:34

1 Answers1

2

Everybody says that we need to make every variable in class private

Since x and y are public fields in Point I believe your assertion that fields must be private is flawed. However, it is usually recommended. Mainly because encapsulation is an important design principle. The linked Wikipedia article says (in part)

A language mechanism for restricting access to some of the object's components

Which is what making a field private does.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249