157 recommendations for writing high-quality code to improve C # programs--Recommendation 104: Replacing conditional statements with polymorphism

Source: Internet
Author: User

Recommendation 104: Using polymorphism instead of conditional statements

Suppose to develop an autonomous driving system. At the beginning of the design, this autopilot system has an enumerated type of driving system command:

    enum Drivecommand    {        Start,        Stop    }

There are currently two commands for this enumeration: Start, stop. Also assume that there is a driving method that can handle the instructions received by the vehicle. At first we might code like this:

        Static voidMain (string[] args) {drivecommand command=Drivecommand.start;            Drive (command); Command=Drivecommand.stop;        Drive (command); }        Static voidDrive (Drivecommand command) {if(Command = =Drivecommand.start) {//vehicle Start-up            }            Else if(Command = =drivecommand.stop) {//Vehicle Stop            }        }

Some people may prefer to use a switch statement (of course, switch is essentially an if statement).

 static void drive        (Drivecommand command) {switchcase Drivecommand.start: //  vehicle start breakcase Drivecommand.stop: // breakdefaultbreak;}   

As more system functions are constantly being developed, we consider adding more and more commands to the vehicle as follows:

    enum Drivecommand    {        Start,        Stop,        Pause,        turnleft,        turnright    }

With the addition of the Drivecommand element, it is obvious that the use of an if or switch statement will bring about a horrible state of chaos. In a complex control system, commands can be as many as hundreds. For each additional life, we first need to modify the drive method. The drive method expands, and each line of code is almost identical:

if command

Then action

In this case, we have to consider refactoring the original code. The original design concept is also not appropriate, it does not adhere to the design pattern of the "open and closed principle." Open and close principle refers to: to expand the development, the modification is closed. A refactoring that follows the open and closed principle is to use polymorphism to circumvent the ever-expanding conditional statements. First, design an abstract class Commander:

    Abstract class Commander    {        publicabstractvoid  Execute ();    }

All commands such as start or stop are inherited from this abstract class:

    class Startcommander:commander    {        publicoverridevoid  Execute ()        {            // start          }    }    class Stopcommander:commander    {           public overridevoid  Execute ()        {            // stop         }    }

After using polymorphism, the code that invokes the method should look like this:

        Static void Main (string[] args)        {            new  startcommander ();            Drive (commander);             New Stopcommander ();            Drive (commander);        }         Static void Drive (Commander Commander)        {            commander. Execute ();        }

As you can see, the code is a lot more concise, and extensibility is enhanced. Even if you need to add more commands in the future, you can extend the corresponding subclasses. And we closed the change, that is, the drive method, even if you add more commands, do not need to modify it.

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

157 recommendations for writing high-quality code to improve C # programs--Recommendation 104: Replacing conditional statements with polymorphism

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.