1

昨天我在玩 jQGrid 插件和 ASP.NET。一切都很好,我的网格现在可以工作了,但是我有两种方法可以让我的代码有异味。

臭臭方法:

private IOrderedEnumerable<Employee> GetOrderedEmployees(Column sortColumn, bool ascending)
    {
        switch (sortColumn)
        {
            case Column.Name:
                {
                    return GetOrderedEmployees(e => e.Name, ascending);
                }
            case Column.Salary:
                {
                    return GetOrderedEmployees(e => e.Salary, ascending);
                }
            default:
                {
                    return GetOrderedEmployees(e => e.ID, ascending);
                }
        }
    }

    private IOrderedEnumerable<Employee> GetOrderedEmployees<TSortKey>(Func<Employee, TSortKey> func, bool ascending)
    {
        return ascending ? Context.Employees.OrderBy(func) : Context.Employees.OrderByDescending(func);
    }

我不知道如何正确重构它们。似乎最好的解决方案是return e=>e.Name在 switch 语句中只返回 lambdas (fe ),但是怎么做呢?

在 switch 语句中,ascending参数被传递了 3 次。不是重复吗?

4

3 回答 3

7

我想你可能在这里过分了。返回 lambdas (IMO) 比简单的 switch 语句或 if;else if;else 块更令人困惑。可能有更好的方法,但有时您确实需要检查条件,尤其是对于列(我讨厌使用 ListViews,但它们是必要的并且通常需要这种代码。)

我认为您不需要重构任何东西。如果该 switch 语句成为维护方面的难题,那么请继续进行,但并非所有 switch 语句都构成“代码异味”。

为了解决您的代码重复问题,您可以使用开关来获取 e.?? 首先是值,将其保存下来,然后在方法结束时调用该函数一次。

于 2009-02-04T23:20:03.733 回答
2

有一些模式可能在这里起作用,但是提供者呢?您可以创建一个提供 GetOrderEmployees 的 Provider,然后传入您想要使用的 Provider 而不是排序列。

编辑 - 但我也认为第一张海报的评论有很多优点 - 无论如何不要为小土豆制定复杂的解决方案。

于 2009-02-04T23:22:47.220 回答
0

如果您只是想减少代码中的重复:

private IOrderedEnumerable<Employee> GetOrderedEmployees(Column sortColumn, bool ascending)
{
    Func<Employee, TSortKey> func = e => e.ID;

    switch (sortColumn)
    {
        case Column.Name:
            {
                func = e => e.Name;
            }
        case Column.Salary:
            {
                func = e => e.Salary;
            }
    }

    return GetOrderedEmployees(func, ascending);
}

private IOrderedEnumerable<Employee> GetOrderedEmployees<TSortKey>(Func<Employee, TSortKey> func, bool ascending)
{
    return ascending ? Context.Employees.OrderBy(func) : Context.Employees.OrderByDescending(func);
}

(我不精通 .NET;请原谅任何语法错误。)

于 2009-02-05T00:08:31.963 回答