Does everyone write something like this [AppleScript] plain text to see the copied code? 1 2 3 4 5 6 7 8 9 if(a){ //dosomething }else if(b){ //doshomething }else if(c){ //doshomething } else{ ////doshomething }
If there’s too many else ifs, then the logic here is going to be confusing and error prone. Like this:
In the beginning, there were fewer conditions, so I didn’t care about so much direct writing; Now I have so many functions that I have to double check every time I add an else condition, for fear of affecting the previous logic. This time I finally had enough and reconstructed it. After reconstruction, the structure here is as follows:
Finally, it becomes two lines of code, which is much simpler. Previously, all implementation logic was extracted separately into other implementation classes.
So whenever I need to add an else logic, ALL I need to do is add a new class that implements the same interface. Each processing logic is independent of each other. implementation
A sketch is drawn based on the current implementation. The idea is as follows: Define an InnerCommand interface with a process function to hand to the specific business implementation. Depending on your business, there are multiple classes that implement the InnerCommand interface; These implementation classes are registered in the Spring Bean container for later use. Get an instance of InnerCommand from the Spring Bean container by entering the command from the client. Execute the final process function. The main goal is to get the InnerCommand instance dynamically based on the current state of the client instead of having multiple criteria. The most important source is the InnerCommandContext class, which dynamically retrieves the InnerCommand instance based on the current client command.
The first step is to get the list of all InnerCommand instances. Get the class type from the list of instances in the first step based on the command entered by the client. Get concrete instance objects from the Spring container based on the class type. Therefore, the first step is to maintain the corresponding class types of each command.
So the relationship between the command and the class type was maintained in the previous enumeration, and you only need to know the command to know its class type. This allows you to replace the previously complex if else with only two lines of code, but also to extend it flexibly. InnerCommand instance = innerCommandContext.getInstance(msg); instance.process(msg) ; The summary can also be made more flexible, for example, there is no need to explicitly maintain the correspondence between commands and class types. Just scan all the classes that implement the InnerCommand interface at startup. There are similar implementations in CICADA, so you can check them out for yourself. I hope these tips will help you.