Ranter
Join devRant
Do all the things like
++ or -- rants, post your own rants, comment on others' rants and build your customized dev avatar
Sign Up
Pipeless API
From the creators of devRant, Pipeless lets you power real-time personalized recommendations and activity feeds using a simple API
Learn More
Comments
-
To make it less likely that you end up with spaghetti code where every block of code depends on the operation of other completely unrelated code.
-
Voxera115733yAlso, encapsulation allows for validation of data you set, for example that to date is after from and similar, or that an amount is within valid range.
An example from a shopping cart, it should mot allow negative amount since you very rarely buy a negative amount of anything.
Or that freight cost or price should not be able to be a negative value.
And even if there are ways around encapsulation you should realize that your on shaky ground ;) -
@electrineer I get it now. If all attributes were public, code readability would be complex which contradicts the paradigm of OOP thats why classes came, alongside encapsulation! ☕ Am I making sense?
-
Voxera115733y@itzdevkou more or less yes.
The idea is to hide internal logic and present an safer interface that should ensure that the object state always is valid, something simple record objects cannot do by them self.
The problem with classes is to know where to draw the line for what should be internal and not.
Most problems comes from to big classes with to much logic that keep to much state so internal state management gets to complex.
But if you start out with only guarding attributes its should rarely get out of hand :) -
@itzdevkou it's not only readability. It enables you to keep structure in your code.
Related Rants
What is the utility of using encapsulation when we can access public attributes. What is the reason behind defining private members?
question
coding
encapsulation
java
android