OOP设计问题-验证属性 [英] OOP Design Question - Validating properties

查看:73
本文介绍了OOP设计问题-验证属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

即使我的程序中没有可以合理输入错误数据的位置,我也总是会验证属性设置程序是否针对错误数据.我的质量检查人员不希望我抛出异常,除非我可以解释异常的发生位置.我应该验证所有属性吗?我可以指出一个标准吗?

示例:

public void setName(String newName){
   if (newName == null){
      throw new IllegalArgumentException("Name cannot be null");
   }
   name = newName;
}

...

//Only call to setName(String)
t.setName("Jim");

解决方案

您正在执行方法的前提条件,这是其合同的重要组成部分.这样做没有任何问题,它还可以用作自我记录的代码(如果我读了您方法的代码,我会立即看到我不应该传递给它的内容),尽管assert可能更适合这样做.

I have the habit of always validating property setters against bad data, even if there's no where in my program that would reasonably input bad data. My QA person doesn't want me throwing exceptions unless I can explain where they would occur. Should I be validating all properties? Is there a standard on this I could point to?

Example:

public void setName(String newName){
   if (newName == null){
      throw new IllegalArgumentException("Name cannot be null");
   }
   name = newName;
}

...

//Only call to setName(String)
t.setName("Jim");

解决方案

You're enforcing your method's preconditions, which are an important part of its contract. There's nothing wrong with doing that, and it also serves as self-documenting code (if I read your method's code, I immediately see what I shouldn't pass to it), though asserts may be preferable for that.

这篇关于OOP设计问题-验证属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆