Using Action dictionaries instead of switch statements

隐身守侯 提交于 2019-11-28 08:10:23

Long switch statements are a classic bad smell, and are always a target for refactoring.

The "standard" step to perform here is Replace Conditional with Polymorphism. This was one of the steps listed in Martin Fowler's book Refactoring (published 11 years ago in 1999).

Now that it's so easy to treat functions like objects (eg with Action) this might be just as good a solution.

And no, I don't think you're being clever for the sake of it. If I wanted to add another option in the future, I can easily see what needs to be done.

Tigran

Depending on your app you can avoid to always construct a new dictionary object, but declare it like a class member, initialize on first access and always return the same instance. But it's hard to say, if it will actually fit your needs. Like this I mean

public class MyClass 
{
   Dictionary<string, Action> dict = null; 

    private Dictionary<string, Action> createView
    {
        get
        {
            if(dict  == null) 
            {
              dict  = new Dictionary<string, Action>()
              {
                {"Standard", CreateStudySummaryView},
                {"By Group", CreateStudySummaryByGroupView},
                {"By Group/Time", CreateViewGroupByHour}
              };
            }

            return dict;
        }
    }

}

EDIT

From conceptual point of view, me replacing long swicth/case with dictionary TryGetValue is a pretty good solution.

Hope this helps...

This approach is excellent.

I use it with more than just Action. It's also quite effective for filters and selectors. Something like:

var filters = new Dictionary<string, Func<MyEntity, bool>>()
{
    // ...
};

var query = entities.Where(filters["X"]);

If the code, once written, is largely static and not subject to too much change then I'd have stuck with a switch. Your dictionary approach here, on the surface at least, lends itself nicely to being more dynamic - that is more requirements based though.

As for replacing switches everywhere with code using this approach, I'd personally not do that in most cases. My honest opinion is that would just be being clever for the sake of it, but it is still easily maintainable. Personal taste over best practise is the largest factor here, as I see it.

On the other hand, as others have said, this could be a workable solution to long switch statements. Then again something like the Strategy Pattern would also be a good way to support changes in behaviour.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!