Do setter and getter methods breaks encapsulation?
据说我们应该避免二传手和接球手。关于它有各种各样的想法,但是根据我的说法,使用这些中断封装。为什么?因为它告诉世界一个物体的内部。例如:
1 2 3 4 5 6 7 8 |
对象应该只公开向客户机提供清晰抽象的行为。
1 2 3 4 5 6 7 |
号
那么,这些访问器和setter方法是否破坏了封装?
从这里开始:
Having getters and setters does not in itself break encapsulation.
What does break encapsulation is having a getter and a setter for
every data member (every field, in java lingo). That is one step away
from making all data members public.The point of encapsulation is not that you should not be able to know
or to change the object's state from outside the object, but that you
should have a reasonable policy for doing it.Consider an example of a class Person. Let's say a person has a name,
a social security number, and an age. Let's say that we do not allow
people to ever change their names or social security numbers. However,
the person's age should be incremented by 1 every year. In this case,
you would provide a constructor that would initialize the name and the
SSN to the given values, and which would initialize the age to 0. You
would also provide a method incrementAge(), which would increase the
age by 1. You would also provide getters for all three. No setters are
required in this case.In this design you allow the state of the object to be inspected from
outside the class, and you allow it to be changed from outside the
class. However, you do not allow the state to be changed arbitrarily.
There is a policy, which effectively states that the name and the SSN
cannot be changed at all, and that the age can be incremented by 1
year at a time.Now let's say a person also has a salary. And people can change jobs
at will, which means their salary will also change. To model this
situation we have no other way but to provide a setSalary() method!
Allowing the salary to be changed at will is a perfectly reasonable
policy in this case.By the way, in your example, I would give the class Fridge the
putCheese() and takeCheese() methods, instead of get_cheese() and
set_cheese(). Then you would still have encapsulation.
号
你也可以参考:为什么getter和setter方法是邪恶的
虽然getter和setter实际上是为了实现封装本身,但它在很大程度上取决于情况本身。
- 糟糕的OO设计:公共领域。
- 有点糟糕的OO设计:当使用getter和setter时,即使在不需要的
- 伟大的OO设计:只在真正需要它们的地方使用——这是为了公开类的行为,而不是用来操作数据的工具。