Does encapsulation of class methods/fields matter if they are only accessed by the class itself?

Viewed 66

Short context: I made a tetris clone in java (all the game data and methods are a Class) and I am concerned about whether encapsulation matters in this case.

Almost all of the fields and methods are marked as "default", without any getters and setters because the user is not supposed to access them.

Methods manipulate variables directly without any arguments passed, of course only when the thing it is manipulating is unique (there can not be two current pieces, two next block lists, two held pieces and so on)

  1. Do I really need getters and setters if the user is never supposed to get raw members of the class? Methods just directly get and set the values. If I have a simple int that I want to get or set, I am just doing it directly.

  2. No return value, if one exact thing is supposed to happen every time. For example: if a collision happens during spawning, gameOver() is triggered immediately instead of returning false, then doing it outside of function. I chose to not have a return value because it is much simpler to do it inside function instead of surrounding each function call with an if statement doing the same thing.

Do I need to fix some of these things, and how should I, preserving stability in both readability and performance?

2 Answers

It does not.

Why? The understanding is that a class’s fields and methods are working in conjunction towards a common goal. So they are not enemies or careless actors that you have to protect yourself against.

It is only to prevent external actors from mucking up class invariants that you hide your fields and methods as much as possible and expose only that which is necessary.

If you have to use setters and getters to enforce discipline in the code within a class, then you have much bigger problems to handle than maintaining proper encapsulation (and other OO principles.)

No, you do not need getters and setters if you do not intend on anything accessing the member variables from outside of the class.

In your case because the member variables are only accessed from within the class itself then the access modifier(s) should be changed to private.

The use of the default keyword means that you do not want to provide an access modifier and that variable should be available to any other class in the same package.

More info can be found Here

Related