c# - 重构帮助c#

标签 c# design-patterns refactoring

我有几百行这样的代码:

if (c.SomeValue == null || c.SomeProperty.Status != 'Y')
{
    btnRecordCall.Enabled = false;
}

if (c.SomeValue == null || (c.SomeProperty.Status != 'Y' &&
    c.SomeOtherPropertyAction != 'Y'))
{
    btnAddAction.Enabled = false;
}

if (c.SomeValue == null || c.SomeProperty.Processing != 'Y')
{
    btnProcesss.Enabled = false;
}

如何正确重构它?我看到每次都会调用检查“c.SomeValue == null”,但它包含在其他条件中。我怎样才能消除这些重复代码?

最佳答案

我会使用 specification pattern ,并构建映射到适当 Enabled 值的复合规范。

您要回答的总体问题是某个对象 c 是否满足给定条件,然后您可以决定是否要启用某些对象。那么你就有了这个界面:

interface ICriteria<T>
{
    bool IsSatisfiedBy(T c);
}

那么您的代码将如下所示:

ICriteria<SomeClass> cr = GetCriteria();

btnAddAction.Enabled = cr.IsSatisfiedBy(c);

下一步是编写合适的 ICriteria 对象。您可以有另一个 ICriteria 实现(除了 Or 和 And),称为 PredicateCriteria,如下所示:

class PredicateCriteria<T>  : ICriteria<T>
{
    public PredicateCriteria(Func<T, bool> p) {
        this.predicate = p;
    }

    readonly Func<T, bool> predicate;

    public bool IsSatisfiedBy(T item) {
        return this.predicate(item);
    }
}

其中一个例子是:

var c = new PredicateCriteria<SomeClass>(c => c.SomeValue != null);

其余的将是这个与其他标准的组合。

关于c# - 重构帮助c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1273686/

相关文章:

java - 在无操作的情况下返回 boolean 值/值而不是 null 是一个好习惯吗?

c++ - xml解析的错误处理

c# - 更优雅的嵌套 Linq 查询解决方案?

c# - 如何将 Switch 与字典值一起使用?

c# - 从抽象类调用GetMethod获取子类的方法?

c# - 在 Reportviewer Azure 中创建 PDF 时出错

java - 有没有办法在没有显式转换的情况下完成这项工作? (尝试通用父子关系)

php - 如何避免大的 switch 语句?

c# - 在 Mvc 中对 Controller 进行简单的 Ajax 调用

ruby - "messy-polymorphism"反模式