2

What is the utility of using encapsulation when we can access public attributes. What is the reason behind defining private members?

Comments
  • 2
    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.
  • 1
    Not every piece of data should have a getter, you know
  • 1
    Also, 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 ;)
  • 0
    @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?
  • 2
    @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 :)
  • 2
    @itzdevkou it's not only readability. It enables you to keep structure in your code.
Add Comment