定义setter返回值
我刚刚在我的一个项目中遇到了问题。也许我对封装的概念有误。 封装通过定义 getters 和 setters 方法来保护类中的成员变量,现在,我读到 setters 必须为 void,但在这种情况下,我如何知道函数是否真正设置了参数传递的值。例如,
void setArea(int a) {
if(a>0)
Area = a;
}
我如何确定参数“a”是正确的值,像这样定义函数不是更好吗
bool setArea(int a) {
if(a>0) {
Area = a;
return true;
}
return false;
}
?这样我就可以知道变化是否真的发生了。
I just had a problem in one of my projects. Maybe I got the wrong concept about encapsulation.
Encapsulation protects member variables from classes, by defining getters and setters methods, now, i was reading that setters must be void, but in that case, how can I know if the function really set the value passed by argument. For example
void setArea(int a) {
if(a>0)
Area = a;
}
How can I be sure that argument "a" was a correct value, wouldnt be better defining the function like this
bool setArea(int a) {
if(a>0) {
Area = a;
return true;
}
return false;
}
Is that ok? that way i can know if a change really happened.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为您正在寻找的是一个 guard 子句,如果设置了无效值,它会引发异常:
但是,如果您希望客户端代码在设置它们之前测试无效值,您可以这样做:
客户端可以这样编码:
但不要就此停止。如果面积的概念很重要,请将其融入到自己的 value 对象 使您的设计更加清晰。
I think what you're looking for is a guard clause that throws an exception if invalid values are set:
But if you want client code to test for invalid values before setting them, you could have this:
Clients could be coded like this:
But don't stop there. If the concept of area is important, spring it into existence into its own value object to make your design clearer.