Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
155 views
in Technique[技术] by (71.8m points)

c# - Using Action dictionaries instead of switch statements

I'm just reviewing some of my old code (have some spare time), and I noticed a rather lengthy switch statement. Due to gaining new knowledge, I have since refactored it in the following form:

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

Would you consider this good practise, or is this simply a case of being superflous and unneccessary? I'm keen to ensure new techniques that I learn, are not being clever just for the sake of it, and that they actually add benefit to the code.

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...