gpt4 book ai didi

c# - 业务对象、验证和异常

转载 作者:IT王子 更新时间:2023-10-29 04:01:10 26 4
gpt4 key购买 nike

我一直在阅读一些关于异常及其使用的问题和答案。似乎强烈认为应该只针对异常、未处理的情况提出异常。所以这让我想知道验证是如何与业务对象一起工作的。

假设我有一个业务对象,其中包含对象属性的 getter/setter。假设我需要验证该值在 10 到 20 之间。这是一个业务规则,所以它属于我的业务对象。所以这对我来说似乎意味着验证代码在我的 setter 中。现在我将我的 UI 数据绑定(bind)到数据对象的属性。用户输入 5,所以规则需要失败,不允许用户移出文本框。 . UI 数据绑定(bind)到属性,因此将调用 setter 、检查规则并失败。如果我从我的业务对象中提出一个异常来说明规则失败,UI 会选择它。但这似乎与异常的首选用法背道而驰。鉴于它是二传手,您不会真正为二传手获得“结果”。如果我在对象上设置另一个标志,则意味着 UI 必须在每次 UI 交互后检查该标志。

那么验证应该如何进行?

编辑:我可能在这里使用了一个过度简化的例子。 UI 可以轻松处理上面的范围检查之类的事情,但是如果验证更复杂怎么办,例如业务对象根据输入计算一个数字,如果计算出的数字超出范围,则应拒绝该数字。这是不应该出现在 UI 中的更复杂的逻辑。

还考虑根据已输入的字段输入更多数据。例如,我必须在订单上输入一个项目以获取某些信息,如手头库存、当前成本等。用户可能需要此信息来决定进一步输入(例如要订购多少单位),或者可能需要它来订购待进一步验证。如果项目无效,用户是否应该能够输入其他字段?有什么意义呢?

最佳答案

您想深入研究 Paul Stovell 的杰出工作关于数据验证。他在this article中一次性总结了自己的想法.我恰好分享了他对此事的观点,我在my own libraries中实现了这一点.

用 Paul 的话说,这是在 setter 中抛出异常的缺点(基于 Name 属性不应为空的示例):

  • There may be times where you actually need to have an empty name. For example, as the default value for a "Create an account" form.
  • If you're relying on this to validate any data before saving, you'll miss the cases where the data is already invalid. By that, I mean, if you load an account from the database with an empty name and don't change it, you might not ever know it was invalid.
  • If you aren't using data binding, you have to write a lot of code with try/catch blocks to show these errors to the user. Trying to show errors on the form as the user is filling it out becomes very difficult.
  • I don't like throwing exceptions for non-exceptional things. A user setting the name of an account to "Supercalafragilisticexpialadocious" isn't an exception, it's an error. This is, of course, a personal thing.
  • It makes it very difficult to get a list of all the rules that have been broken. For example, on some websites, you'll see validation messages such as "Name must be entered. Address must be entered. Email must be entered". To display that, you're going to need a lot of try/catch blocks.

这里是替代解决方案的基本规则:

  1. There is nothing wrong with having an invalid business object, so long as you don't try to persist it.
  2. Any and all broken rules should be retrievable from the business object, so that data binding, as well as your own code, can see if there are errors and handle them appropriately.

关于c# - 业务对象、验证和异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/88541/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com