Short answer: You want to minimize unwanted interactions by publishing as few components as possible, so that it still does its part and ensuring that the component works as close as possible in the application, since it behaves in isolation (there, where it can be easily tested).
Longer answer: Type methods represent his contract, while his variables represent his state. Any nontrivial type will contain several member variables with their own interrelated states. As the evolution offered by this type (its contract) develops (new or advanced functions, bug fixes), the programmer must keep in mind all these relationships in order to make sure that the existing behavior does not break.
A well-established way to achieve this is to write Unit Tests, but this only confirms the type in isolation. By minimizing the presentation of the type state and limiting it to well-understood and planned operations, the programmer tries to minimize model failures that he or she was able to verify.
In contrast, if external components have ways to access the state of the component beyond those planned by the developer of this type, it is easy for them to inadvertently disrupt its behavior. And the interactions between the components are exponential: in my experience, when a program spans over 20,000 lines of code, the author of several developers, each of which specializes in separate modules, and goes through several versions, no one will have an ideal idea of ββthe whole code anymore.
Many books and articles have been written on this subject, and I am sure that they will be more eloquent and convincing than I can be. For general Java recommendations, I highly recommend Josh Bloch Effective Java (2nd Edition).
source share