If-Else and switch-case are judgment logic statements. As long as we need to branch them, we may need to use such statements. In C's programming style, such judgment statements are even more dynamic, the problem is that if this judgment statement is too large, it will destroy the readability and maintainability of the code and increase the Code's "bad smell ". In the current Object-Oriented Programming age, do we have some methods to replace it? Well, yes. The polymorphism and template features provided by C ++ are very suitable for writing code that replaces if-Else and switch-case.
Let's give a simple example. The check function checkevent (INT nevent) of an event determines the arrival of the event and performs corresponding operations. If you use if-else or switch-case, the Code is as follows:
// Use the IF-else Function
Void checkevent (INT nevt)
{
If (nevt = 1)
Cout <"1" <Endl;
If (nevt = 2)
Cout <"2" <Endl;
}
// The Call Code is as follows:
Void main ()
{
Int nevent = 1;
Checkevent (nevent );
Int nevent = 2;
Checkevent (nevent );
}
Here we replace it with Polymorphism:
// The first method to replace if-Else
Class cevent
{
Public:
Virtual void show () = 0;
};
Class cevent1: Public cevent
{
Public:
Virtual void show ()
{
Cout <"1" <Endl;
}
};
Class cevent2: Public cevent
{
Public:
Virtual void show ()
{
Cout <"2" <Endl;
}
};
Void checkeventnoifelse (cevent * pevt)
{
Pevt-> show ();
}
// The Call Code is as follows:
Void main ()
{
// The first polymorphism Technology
Cevent1 evt1;
Cevent2 evt2;
Checkeventnoifelse (& evt1 );
Checkeventnoifelse (& evt2 );
}
Let's see the usage of polymorphism. In the checkevent, there is no need to judge the code again.
Polymorphism is a dynamic method. We can also use the template Technology (a static method ):
// The second method to replace if-Else
Template <class T>
Void checkeventtemplate (T * EVT)
{
EVT-> show ();
}
// The Call Code is as follows:
Void main ()
{
// Second template Technology
Cevent1 evt1;
Cevent2 evt2;
Checkeventtemplate (& evt1 );
Checkeventtemplate (& evt2 );
}
In addition, we can also use some design patterns to replace the code used to determine the selected if-else switch-case. For example, the State mode is a good way to replace switch-case, I also mentioned in agile. You can also refer to my "state mode of simple code in design mode". The actual state mode uses the delegation and polymorphism Technology in C ++.
Well, I have mentioned some methods above. I hope they will be useful to you. In addition, they may not be completely summarized. I hope that you will not be enlightened by other methods. Thank you!