当前位置:  开发笔记 > 编程语言 > 正文

如何在ASP.NET MVC中使用DRY原则来重构此代码?

如何解决《如何在ASP.NETMVC中使用DRY原则来重构此代码?》经验,为你挑选了1个好方法。

我的一个控制器中有几种方法可以做到这一点:

ViewData["Customers"] = LoadCustomers();
ViewData["Employees"] = LoadEmployees();
ViewData["Statuses"] = LoadStatuses();
etc......

这是LoadCustomers(),但LoadEmployees,LoadStatuses和所有其他几乎完全相同的逻辑:

private static SelectList LoadCustomers()
    {
        IList customers;
        try
        {
            IServiceCallService scService = new ServiceCallService();
            customers = scService.GetCustomers();
            Customer c = new Customer
            {
                ID = "",
                Name = "-- Select a Facility --"
            };
            customers.Insert(0, c);
        }
        catch
        {
            customers = new List();
            Customer c = new Customer
            {
                ID = "",
                Name = "-- No Facilities on File --"
            };
            customers.Insert(0, c);
        }

        return new SelectList(customers, "ID", "Name");
    }

如何更好地编写此代码,以便每次添加新的选择列表时都不需要新方法?



1> John Feminel..:

看起来它可能是泛型的一个很好的候选者:

private static SelectList LoadItems() where T : new, ... 
{                                                // Add any additional interfaces
                                                 // that need to be supported by T
                                                 // for your Load method to work,
                                                 // as appropriate.
    IList items;
    try
    {
        IServiceCallService scService = new ServiceCallService();
        results = scService.Get();  // You'll need to replace GetCustomers() with
                                       //   a generic Get method.

        // ...
    }
    catch         // Really needed? What are you trying to catch here? (This catches
    {             //   everything silently. I suspect this is overkill.)
        // ...
    }

    return new SelectList(items, "ID", "Name");
}

推荐阅读
mylvfamily
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有