Reduce code redundancy and encapsulate your program

Source: Internet
Author: User

I saw a problem on the forum just now. Some netizens posted a method as follows. Excessive code redundancy excessive if judgment.



The following Insus. NET reconstructs this method according to its own method and habits. It is hoped that the Code redundancy can be simplified and encapsulated.
Step 1: You can see that each if judgment block contains one sentence:

FileUpload. PostedFile. SaveAs (myDicPath ++ fileName );


The result is as follows. The redundant items are all written out by Insus. NET comment, leaving only one sentence of Highlight:



Step 2, we can see that each if judgment block contains two codes to determine whether the directory exists. if not, create a directory.

(!


We can encapsulate it into a method:


After reconstruction, it looks like this:



Step 3: The Insus. NET idea of this multiple if judgment blocks is to remove the if judgment. Impossible! Yes. Let's take a look at the reconstruction process below. Before implementation, plan the Directory and file extension:



Write another method with a parameter and pass in the extension type name of the file to obtain the directory name.



OK. Now we can refactor the program again:


Well, remove the comment out code and leave it:




If you really don't want an if, you can refactor the following method of else:



Sorry, the last supplementary method mentioned above is a little problematic. Therefore, Insus. NET can be reconstructed as follows:


That is to say, immediately break the foreach loop after finding the matching.

Check the test results:


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.