"Go" writing high-quality Code 157 recommendations for improving C # programs--Recommendation 149: Using table-driven methods to avoid too long if and switch branches

Source: Internet
Author: User

Recommendation 149: Avoid too long if and switch branches with table-driven methods

As the code becomes more complex, we can easily be bothered by too long if and switch branches.

A class enumeration type week is as follows:

    enum Week    {        Monday,        Tuesday,        Wednesday,        Thursday,        Friday,        Saturday,        Sunday    }

If you want to export week element values in Chinese, a simple and ugly approach might be to encapsulate a Getchineseweek method:

        Static stringGetchineseweek (Week Week) {Switch(week) { CaseWeek.monday:return "Monday";  CaseWeek.tuesday:return "Tuesday";  CaseWeek.wednesday:return "Wednesday";  CaseWeek.thursday:return "Thursday";  CaseWeek.friday:return "Friday";  CaseWeek.saturday:return "Saturday";  CaseWeek.sunday:return "Sunday"; default:                    Throw NewArgumentOutOfRangeException ("Week","Week value out of range"); }        }

The reason that this method is too ugly is because:

1) The branch is too long and there is a duplicate code.

2) not conducive to expansion. What if there is a week, eight, and nine weeks? Of course, the week system is already fixed, and there should be no expansion. But, in a different scenario, suppose we're rendering an animation? Who knows how many animations will the American union submit to me next second?

One solution is to use polymorphism, which fits well with the "open and close" principle. If you add a conditional branch, you do not have to modify the source code to add the subclass directly. Using polymorphism to avoid branching, this is not a table, this recommendation is to adopt the "table-driven method."

The table driver can be simply understood as a dictionary. The code is indicated as follows:

        Static stringGetchineseweek (Week Week) {string[] Chineseweek = {"Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday" }; returnchineseweek[(int) week]; }        Static voidMain (string[] args)        {Console.WriteLine (Getchineseweek (Week.friday)); }

This is a table-driven method driven by index values. The integer value represented by the enumeration element, which is easily combined with the string array index, resolves the Getchineseweek method with two lines of statements. However, this approach has limitations, if necessary: Monday Mike Cleaning, Tuesday rose clean up the wardrobe, Wednesday Mike and rose nothing can quarrel, Thursday rose to go to shopping, that is, demand from static properties into dynamic behavior, then things become complex.

In this case, we may think of using polymorphism, where the table-driven method is still used to implement this dynamic behavior with a little reflection, the code is as follows:

    classProgram {Static stringactionintable (Week Week) {string[] methods = {"Cleaning","Cleancloset","Quarrel","Shopping","Temp","Temp","Temp" }; returnmethods[(int) week]; }        Static voidMain (string[] args) {SampleClass Sample=NewSampleClass (); varAddmethod =typeof(SampleClass).            GetMethod (Actionintable (week.monday)); Addmethod.invoke (Sample,NULL); }    }    classSampleClass { Public voidCleaning () {Console.WriteLine ("Cleaning"); }         Public voidCleancloset () {Console.WriteLine ("Organize your wardrobe"); }         Public voidQuarrel () {Console.WriteLine ("Quarrel"); }         Public voidShopping () {Console.WriteLine ("Shopping"); }         Public voidTemp () {Console.WriteLine ("Temporary Arrangements"); }    }

Table-driven method is a kind of design idea, also can be called pattern. In the actual coding, it should not be confined to the index to drive the behavior, but should be applied flexibly according to the actual situation.

Turn from: 157 recommendations for writing high-quality code to improve C # programs Minjia

"Go" writing high-quality Code 157 recommendations for improving C # programs--Recommendation 149: Using table-driven methods to avoid too long if and switch branches

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.