Encapsulation Vs Plain

前端 未结 4 1774
你的背包
你的背包 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:45

    One way to use encapsulation is to hide implementation. Sometimes a getter, for example, isn't a getter. Consider a shape like a sphere, I wouldn't necessarily store the volume or surface area as a variable because I could calculate them at any time. I would still call the member functions getVolume and getSurfaceArea. The person who uses my code doesn't need to know if I calculate or simply store the value. By exposing my variables I lock them into a design decision that would have to change (or be broken) should I change my implementation. By hiding implementation you need only know the interface (not to be confused with Java's 'interface' ) It protects everybody that way and makes making future changes a much easier task.

    It should be noted that there are times when setters/getter are not used and variables are exposed. Even in Java sometimes it just makes more sense not to hide instance variables.

提交回复
热议问题