旧的验证代码通常检查布尔条件,如果条件成立则抛出异常。
相反,Contract.Requires(...) 执行相反的操作(为了通过检查,我们需要否定旧条件)。
我正在重构旧代码,有时会看到一些相当高级的布尔语句,反转它们并不那么容易,并且仅仅执行 Contract.Requires(!(*old statements*))
看起来很糟糕并且非常令人困惑。
如果它有类似 Contract.RequiresNot()
的东西,重构在这里会更加清晰和直接。
我们也无法添加静态扩展方法。如果有人遇到这个问题并找到了一些好的解决方案,我很想听听。
Old validation code is usually checking a boolean condition, and throws an exception if that is true.
Instead Contract.Requires(...)
does the opposite (to pass the check we need to negate old condition).
I am refatoring old code and sometimes see some fairly advanced boolean statements, inversing them isn't that easy, and just doing Contract.Requires(!(*old statements*))
appears bad and very confusing.
If it had something like Contract.RequiresNot()
refactoring would be much more clear and straightforward here.
We also cannot add a static extension method. If someone encountered this problem and found some good solution I would like to hear it.
发布评论
评论(2)
您可以尝试保留旧的遗留验证并添加
You could try leaving the old legacy validations in place and adding a Contract.EndContractBlock call immediately following the validations. From MSDN:
您可以将
旧语句
的结果存储到具有适当名称的布尔变量中。这将摆脱一对令人困惑的括号,并且还可以自我记录您的代码=)You could store the result of
old statements
in to a boolean variable with a proper name. That would get rid of the pair of confusing parenthesis and also serve to self-document your code =)