C # generic coding simplicity (how to write brief C # code and update it at any time)

Source: Internet
Author: User

Author: Chen Yong

Source: blog.csdn.net/cheny_com

This is one of the series on encoding simplicity. previous articles include code, functions, and semantics. Because cases need to be accumulated, they will be updated at any time.

 

As mentioned earlier, the "heart" of code simplicity is that there must be a merge approach as long as there are two pieces of code on the screen that look similar. Speaking of similarity, there is no more similar code than the switch-case code. If you look at the longest function in your product, there is almost certainly a switch-case, or a bunch of IF-else if (the two are actually equivalent ). Generally, the codes in each section seem to be the same and a little different. They cannot be converted into functions or classes. What should I do?

The best solution to the smelly switch-case is generics (called templates in the C ++ era ). Generics are hard to learn, but important. 02 code reviews were conducted as process improvement personnel in about a year. I accidentally found a piece of code that was fluctuating during Pagedown, we can see that 65 of them can actually be reduced to 1 function (correct, 65: 1). The content is to process 13 different variables under 5 Int constants, the processing method is the same. There are a total of 4000 lines of code in this section, which has taken a month, and the programmer's monthly salary is 7000 (that was 10 years ago, 7000 yuan can buy 5 square meters of small property houses, or 2 square meters of large property houses ); in the afternoon, they became a function with less than 55 rows in length. It is inferred that the annual economic losses caused by the inability to use generics flexibly may exceed RMB.

Case 1 A Simple generic class

The following code is very short and is not worthy of transformation. However, in addition to display, there are many functions, some of which have a long case and various types will emerge one after another, so we have to modify them.

The purpose of display is to enable various UDC users to display values in their own ways:

        public static MvcHtmlString Display(this HtmlHelper htmlHelper, UDC udc)        {            switch (udc.Type)            {                case "Text100":                    return new MvcHtmlString((udc.Value != null) ? udc.Value.ToString() : "NULL");                case "Text20":                    return new MvcHtmlString((udc.Value != null) ? udc.Value.ToString() : "NULL");                case "Date":                    return new MvcHtmlString(((DateTime)udc.Value).ToShortDateString());                default: return new MvcHtmlString(string.Format("Unknown UDC type: {0}", udc.Type));            }        }

To be able to disassemble this function, you need to declare

    public interface IUDC    {        ……        MvcHtmlString Display { get; }        ……    }

Then let a class (this class usually exists) inherit this interface and implement its method:

    public partial class UDCText100 : IUDC     {        ……        public MvcHtmlString Display { get { return new MvcHtmlString((Value != null) ? Value.ToString() : "NULL"); } }        ……    }

The display mode also changes from @ html. Display (UDC) to @ UDC. display.

After the entire modification of this Code, only one switch-case exists, and the code is obviously more cohesive, that is, a type is added each time, you only need to complete the modification in one place (partial class; the modified results can be confirmed to be sufficient and correct during compilation (but a type is missing in switch-case, which can only be found when the case is not found ).

Case 2 generic functions

        private IUDC GetOrDefaultUDC<T, V>(Table<T> table, ..., V defaultValue) where T : class, IUDC, new()        {            var t = table.SingleOrDefault(...);            if (t == null)            {                t = new T();                ...                t.OValue = defaultValue;                 ...            }            return t;        }

This generic function extracts a record from a type of table. If no record exists, it is created. Because a new record is required during creation, and the new record is based on different tables, the default values of some fields are also different. Many functions need to be written in the traditional method, and every time a new type of table appears, new functions need to be written. The 65 functions mentioned at the beginning of this article are generated accordingly.

The core method to deal with such situations is:If you find that some code that looks like a lot different types cannot be merged into functions, you should use generics..

In this case, two main technologies need to be mastered to use generics: New () and ixxx (an interface ). The purpose of New is to allow t to be created (not required if the function is not created ), the purpose of the interface is to ensure that the function can still be used by new types in the future at the Compilation Time (the C ++ ERA can only be confirmed when new types are used ).

 

Here we only talk about the application of generic thinking, on the application of generic technology, there is a good article in msdn for reference: http://msdn.microsoft.com/en-us/library/ms379564 (V = vs.80). aspx. This article describes the development history of C # generics from the beginning to the end.

 

Click to download the free agile development textbook: Martian agile development manual

 

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.