Refactor if... else... or switch block, if... else... switch

Source: Internet
Author: User

Refactor if... else... or switch block, if... else... switch

When developing asp.net, we often use if... else... or switch to judge multiple conditions. As shown in the following article "user control use event Ver2" http://www.cnblogs.com/insus/archive/2011/11/18/2253605.html,? code:


In fact, there is no problem in writing the code above, but it seems that we have to spend some time reading this code during the review. The intention is not clear enough, and the coupling is high.

We recommend that you write each case block as an independent method. Then call it to minimize the number of methods.


In this way, the program can be changed:


Here, we need to review the design pattern Mediator Pattern, more examples can refer to the design pattern-Mediator Pattern http://www.cnblogs.com/insus/p/4134383.html and development (ASP. NET Program) write the code to the most object-oriented taste, http://www.cnblogs.com/insus/p/4139346.html. That is,When there are multiple if or switches, we can use the intermediary design pattern to solve the problem. To put it bluntly, we will replace it.

Next we will create an intermediary:


After writing, we can reconstruct the switch program:


Run the demo in real time and get the same results as the original one:


This article tells us that the program is not written once, but can be well written only after reconstruction. After the house is built, it can only be a rough room, it needs to be decorated, Insus. NET's understanding of refactoring is to make some changes when there is not much change to the original nature, which is suitable for comfort. At the same time of reconstruction, it is often carried out with the design pattern concept.

This demo source program can be downloaded from the following link:
Http://download.cnblogs.com/insus/Refactoring/fact_switch_mediator_pattern.rar

 

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.