首页 > 解决方案 > 如何定义和执行约束分层实体的复杂规则

问题描述

如果我有一个Policy,这Policy应该由Sections(固定数字)组成。

我的部分是 4 个预定义的部分:

每个Section都有固定的属性,不同于其他部分的属性。如果我可以用一个类比来说明:

例如:

注意:根据领域专家的解释:他希望每个部分都有一个Save操作(作为草稿),以便他可以更新该部分,除非策略尚未提交,并且整个 Policy 的Submit操作以便在策略提交之后任何人都不能更新或删除本政策或其部分。(任何需要的更新 = 定义新策略)


现在我想设计Policy,Sectionits content. 但我卡住了。

首先,我认为我可以设计为Policy实体(聚合根)并创建类,four每个类一个Section并从.Section base class(Id,name)PolicySection


其次,我用以下方式引导我的思想概括部分内容:

我将创建:

然后我将创建参考表SectionRules:

前任:

rule-key         |default-value|operators|section-type|value-type|rule-type

NumOfhoursInMonth| 5:00        |  =      |  2         | String      |Assignment 
AvailableExcuses |2:00,2:30    |  IN     |  2         | List<String>|Relational 

备注:

当用户启动时,Policy我将遍历 ref 表以在表单中列出规则,以便他可以default values根据其类型更改并将它们保存在 Section 中,如下所示:

  Id   |Name       |Rule                   |section-type
  1    |Excuses    |NumOfhoursInMonth <= 6 |   2

我现在面临两个问题。

  1. 如果其中一些相互依赖,如何关联不同的规则?例如NumOfExcuses'hoursInMonth Should be less than or equal 6:00 根据第一条规则,但是如何防止用户在设置第二条规则时违反此规则如果他设置了 AvailableExcuses IN(5:00,7:00)!现在我应该阻止用户添加大于的数字,6因为第一条规则限制了第二条规则?第二条规则与第一条规则不一致,因为列表包含(07:00)并且第一条规则声明totalExcuseshoursInMonth <= 06:00 hours
  2. 如何使规则更具表现力以允许条件规则和其他规则?

我在正确的方向吗?我能得到一些建议吗?

标签: c#validationdesign-patternsdomain-driven-designrule-engine

解决方案


我不完全确定哪种设计最合适,您肯定会经历多次模型迭代,直到您满意为止,但我认为问题的核心,我认为是编写规则并找到冲突的规则可以解决使用规范模式。规范模式基本上包括使规则成为模型的一等公民,而不是仅通过条件语言结构来表达它们。

有很多方法可以实现该模式,但这里有一个示例:

规格模式

在我设计的其中一个系统1中,我设法重用一组相同的规范来强制执行命令和查询的授权规则以及强制执行和描述业务规则。

例如,您可以describe(): string在规范中添加一个负责描述其约束的toSql(string mainPolicyTableAlias)方法或一个可以将其转换为 SQL 的方法。

例如(伪代码)

someSpec = new SomeRule(...).and(new SomeOtherRule(...));
unsatisfiedSpec = someSpec.remainderUnsatisfiedBy(someCandidate);
errorMessage = unsatisfiedSpec.describe();

但是,直接在规范上实施此类操作可能会因各种应用程序/基础架构问题而污染它们。为了避免这种污染,您可以使用访问者模式,这将允许您在正确的层中对各种操作进行建模。但是,这种方法的缺点是每次添加新类型的具体规范时都必须更改所有访问者。

访客模式

#1 为此,我必须实现上述论文中描述的其他规范操作,例如remainderUnsatisfiedBy等。

自从我用 C# 编程以来已经有一段时间了,但我认为C# 中的表达式树可以非常方便地实现规范并将它们转换为多种表示形式。

验证策略每个部分中不同规则之间的相关性

我不完全确定您在这里的想法,但是通过添加诸如conflictsWith(Spec other): bool在您的规范上的操作,您可以实现一种冲突检测算法,该算法会告诉您一个或多个规则是否存在冲突。

例如,在下面的示例中,两个规则都会发生冲突,因为它们不可能都为真(伪代码):

rule1 = new AttributeEquals('someAttribute', 'some value');
rule2 = new AttributeEquals('someAttribute', 'some other value');
rule1.conflictsWith(rule2); //true

总之,您的整个模型肯定会比这更复杂,您必须找到描述规则并将它们与正确组件相关联的正确方法。您甚至可能希望将某些规则与适用性规范联系起来,以便它们仅在满足某些特定条件时才适用,并且您可能有许多不同的规范候选类型,例如Policy,Section或者SectionAttribute考虑到某些规则可能需要应用于整体Policy而其他类型规则必须在给定特定部分的属性的情况下进行解释。

希望我的回答能激发一些想法,让您走上正轨。我还建议您查看现有的验证框架和规则引擎以获取更多想法。另请注意,如果您希望整个规则和状态Policy始终保持一致,那么您最有可能将其设计Policy为由所有部分和规则组成的大型聚合。如果由于性能原因或并发冲突(例如,许多用户编辑同一策略的不同部分)以某种方式不可能也不可取,那么您可能会被迫分解大型聚合并改用最终一致性。

当现有状态被新规则无效时,您当然还必须考虑需要做什么。也许您会想要强制同时更改规则和状态,或者您可以实施状态验证指示器以将当前状态的一部分标记为无效等。

1-你能解释一下describe(),toSql(string mainPolicyTableAlias)吗,我不明白这些函数背后的意图。

好吧,describe将给出规则的描述。如果您需要 i18n 支持或对消息的更多控制,您可能希望使用访问者,也许您还需要一个功能,您可以使用模板消息等覆盖自动描述。toSql方法相同,但生成例如,可以在WHERE条件内使用什么。

new Required().describe() //required
new NumericRange(']0-9]').if(NotNullOrEmpty()).describe() //when provided, must be in ]0-9] range

这是一个相当大的缺点!请问如何解决这个问题。

直接在对象上支持行为可以很容易地添加新对象,但更难添加新行为,而使用访问者模式可以很容易地添加新行为,但更难添加新类型。这就是著名的表达式问题

如果您可以找到一个不太可能针对所有特定类型更改的通用抽象表示,则可以缓解该问题。例如,如果您想绘制多种类型的Polygon,例如TriangleSquare等,您最终可以将它们全部表示为一系列有序点。一个规范当然可以分解为一个表达式在此处探讨),但这并不能神奇地解决所有翻译问题。

这是 JavaScript 和 HTML 中的示例实现。请注意,某些规范的实现非常幼稚,并且无法很好地处理 undefined/blank/null 值,但您应该明白这一点。

class AttrRule {
  isSatisfiedBy(value) { return true; }
  and(otherRule) { return new AndAttrRule(this, otherRule); }
  or(otherRule) { return new OrAttrRule(this, otherRule); }
  not() { return new NotAttrRule(this); }
  describe() { return ''; }
}

class BinaryCompositeAttrRule extends AttrRule {
  constructor(leftRule, rightRule) {
    super();
    this.leftRule = leftRule;
    this.rightRule = rightRule;
  }
  
  isSatisfiedBy(value) {
    const leftSatisfied = this.leftRule.isSatisfiedBy(value);
    const rightSatisfied = this.rightRule.isSatisfiedBy(value);
    return this._combineSatisfactions(leftSatisfied, rightSatisfied);
  }
  
  describe() {
    const leftDesc = this.leftRule.describe();
    const rightDesc = this.rightRule.describe();
    return `(${leftDesc}) ${this._descCombinationOperator()} (${rightDesc})`;
  }
}

class AndAttrRule extends BinaryCompositeAttrRule {
  _combineSatisfactions(leftSatisfied, rightSatisfied) { return !!(leftSatisfied && rightSatisfied); }
  _descCombinationOperator() { return 'and'; }
}

class OrAttrRule extends BinaryCompositeAttrRule {
  _combineSatisfactions(leftSatisfied, rightSatisfied) { return !!(leftSatisfied || rightSatisfied); }
  _descCombinationOperator() { return 'or'; }
}

class NotAttrRule extends AttrRule {
  constructor(innerRule) {
    super();
    this.innerRule = innerRule;
  }
  isSatisfiedBy(value) {
    return !this.innerRule;
  }
  describe() { return 'not (${this.innerRule.describe()})'}
}

class ValueInAttrRule extends AttrRule {
  constructor(values) {
    super();
    this.values = values;
  }
  
  isSatisfiedBy(value) {
    return ~this.values.indexOf(value);
  }
  
  describe() { return `must be in ${JSON.stringify(this.values)}`; }
}

class CompareAttrRule extends AttrRule {
  constructor(operator, value) {
    super();
    this.value = value;
    this.operator = operator;
  }
  
  isSatisfiedBy(value) {
    //Unsafe implementation
    return eval(`value ${this.operator} this.value`);
  }
  
  describe() { return `must be ${this.operator} ${this.value}`; }
}

const rules = {
  numOfHoursInMonth: new CompareAttrRule('<=', 6),
  excuseType: new ValueInAttrRule(['some_excuse_type', 'some_other_excuse_type']),
  otherForFun: new CompareAttrRule('>=', 0).and(new CompareAttrRule('<=', 5))
};

displayRules();
initFormValidation();

function displayRules() {
  const frag = document.createDocumentFragment();
  Object.keys(rules).forEach(k => {
    const ruleEl = frag.appendChild(document.createElement('li'));
    ruleEl.innerHTML = `${k}: ${rules[k].describe()}`;
  });
  document.getElementById('rules').appendChild(frag);
}

function initFormValidation() {
  const form = document.querySelector('form');
  form.addEventListener('submit', e => {
    e.preventDefault();
  });
  form.addEventListener('input', e => {
    validateInput(e.target);
  });
  Array.from(form.querySelectorAll('input')).forEach(validateInput);
}

function validateInput(input) {
    const rule = rules[input.name];
    const satisfied = rule.isSatisfiedBy(input.value);
    const errorMsg = satisfied? '' : rule.describe();
    input.setCustomValidity(errorMsg);
}
form > label {
  display: block;
  margin-bottom: 5px;
}

input:invalid {
  color: red;
}
<h3>Rules:</h3>
<ul id="rules"></ul>

<form>
  <label>numOfHoursInMonth: <input name="numOfHoursInMonth" type="number" value="0"></label>
  <label>excuseType: <input name="excuseType" type="text" value="some_excuse_type"></label>
  <label>otherForFun: <input name="otherForFun" type="number" value="-1"></label>
</form>


推荐阅读