3 ms·
As software projects grow, development really becomes an exercise in managing complexity. One of the benefits of encapsulating state and functionality into cla
by jason-m-b 4y ago
As software projects grow, development really becomes an exercise in managing complexity. One of the benefits of encapsulating state and functionality into classes is to reduce the amount of coupling that can occur between components. By coupling, I mean the dependence of one component on the specific behavior or implementation details of another component.
There will always be some amount of coupling, but reducing it makes it much easier to reason in your mind about small sections of code. With good encapsulation, there are clear interfaces between components and it is difficult to use them incorrectly.
You could argue that if there are only a few or even one developer on a project, there is no harm in making everything public since everyone will just use the class "correctly". However, the "correct" way to use the class is not codified or enforced anywhere other than the minds of the developers, comments, or external documentation. All of these sources can easily fall out of sync with the actual code being written. The compiler/runtime should be used to enforce correct usage when possible. This greatly reduces the cognitive load on the developer/s since they know if the code compiles or runs without error, a whole class of bugs has already been eliminated.
I would argue that even if access controls were completely ineffective (they didn’t actually control access), they would still be useful as API documentation within the source code to point others and your future self to the set of variables and functions that should be used to interact with the class. There is a benefit to writing code that is itself expressive of intent without requiring additional documentation or knowledge.
Another reason to reduce coupling is to make it easier to re-implement a single component of the system. If the component was well encapsulated and has a clean and minimal public interface, the only restriction on the new implementation is to meet that same public interface. If the component was not well encapsulated, the new implementation may have to maintain a number of details from the previous implementation than no longer make sense just to maintain all of the unnecessary coupling that’s been created between the component and the code that uses it.