Encapsulation Vs Plain

前端 未结 4 1783
你的背包
你的背包 2021-01-19 22:05

Why should I use encapsulation if the code below will produce the same result?

The main benefit of encapsulation is the ability to mo

4条回答
  •  余生分开走
    2021-01-19 22:36

    1. By providing getters and setters we get the benefits of hiding the implementation. e.g. You can use lazy initialization, proxies etc.
    2. Code becomes more maintainable e.g. you can easily add pre and post checks (or validations) at one place. If you access the variable directly and later on you need to add any validation or some default behaviour while reading the value you would have to change it at multiple places.
    3. By getters and setters you get the benefits of polymorphism. e.g. if you don't want value of the variable to be changed in extended version or vice versa, you can simply throw exception.

    From debugging point of view:

    1. Provides the segregation of code lines where the variable's value is accessed or updated. (Can be used to check references)
    2. Sometimes, we need to know where the value of variable got changed. You can put debug pointer or logger to investigate it.

提交回复
热议问题