DOCX

Talk about extension methods, from the string

By Jill Baker,2015-10-03 22:56
18 views 0
Talk about extension methods, from the string

    String. IsNullOrEmpty () this method is one of most frequently used method in the net.This method is a static method of the string similar static method in the string class and lots more.Such methods as a static method is reasonable?If we set off from the view of object-oriented, we will find that this approach is not very accord with object-oriented design principles.

    What is the object?Object is have a combination of data and behavior.If the string is a class, then the string message = "hello" this sentence is defined a string object, called the message.

    A. Let objects speak for themselves

    Object should be autonomous, it has its own behavior and data.If the object as a living, he can speak for themselves.For example, we treat the message as a person, can appear the following dialogue:

    A: "hi message, you are empty?"

    B: "no."

    A: "what is the length of you?"

    B:"5"

    This dialogue embodies the message as an object, have their own behavior and data.

    The code string. IsNullOrEmpty (message) describes the following dialogue:

    A: "Hi string, the message is empty?"

    B: "no"

    Obviously, the back of the dialogue with the help of the string class to complete this should be the message object should be done.So we say this design has not completely conform to the principle of object-oriented design.If this design also can say that in the past, after all, the string class and the relationship between the message object is a little bit.The following this scenario is more unreliable:

    You want to implement reverse a string (reverse), open the string class view, found..net is not this way, so you create a class that is StringHelper and wrote the following code:

    public static string Reverse(string originalString)

     {

     return something;

     }

    If the code will talk, will have the following dialogue:

    A: "hi StringHelper, put the message reversal"

    This conversation has exposed the two questions:

    1. Coupling the StringHelper category, the user must be aware of such

    a class, the user know too much.

    2. The behavior of the inversion are objects themselves, but they did

    not achieve.

    Of the extension method "to remedy", the code can be written as follows: the message. The IsNullOrEmpty (), isn't that what we want?Ruby as an object-oriented language, in the design is noticed at the beginning of this question: in the irb input: String. Instance_methods (false) can see all of the String instance methods, for example: the empty?, : the size, : reverse, can be directly written in Ruby: message. The empty?

    In fact, the word "remedy" is not accurate, because no one can take account of all the behavior to the object at the beginning of design, the extension methods is more we extend the user behavior provides a solution.New programming language, such as f #, Ruby, swift etc. Provide the object extension ability.

    Extension method can perfectly solve the problem of the expansion of the object behavior.You have in your project, such as * * Helper, * *, such as the Utility class?Most of the code inside can become an object of extension methods.

    2. Simulated infix operators

    In c # +, -, *, / and other operators are infix expression, such as to use the operator "+" three connection string:

    "stringA"+"stringB"+"stringC";

    If you use a function you will need to write:

    string.Contact(“stringA”,string.Contact(“stringB”,”stringC”));

    After a written question is written sequence of operation and its practical execution order instead, so using the operator without the advantage of using

    the function is described in the code to read "infix" operator more natural.Extension methods can be used to simulate the infix operators to some extent.

    A Rectangle has a static method of the Union: public static Rectangle Union (Rectangle a, a Rectangle b);We can't say the Union this static method should be a behavior of a Rectangle.The performance of this method is more out of the two Rectangle doing the Union operation, using the extension method: internal static Rectangle Union(this Rectangle @this,Rectangle anotheRectangle)

     {

     return Rectangle.Union(@this, notheRectangle);

     }

    Can be very natural to write:

    var unionRegion = r1.Union(r2).Union(r3);

    Instead of:

    var unionRegion = Rectangle.Union(r1, Rectangle.Union(r2, r3));

    Third, oriented programming language

    Consider the following extension method and call:

    public static TimeSpan Days(this int @this)

     {

     return TimeSpan.FromDays(@this);

     }

     var timeSpan = 3.Days();

    Under this scenario, the Days () is neither int behavior, also is not operation, but have a little taste for language programming.In object-oriented programming environment, there is a style of programming is called smooth Interface API (Fluent), such programming scene is mostly used in the class library API design, the design of the Interface of Fluent seeWith c # design

Fluent InterfaceandIn c # using the decorator pattern and extension methods to

    achieve Fluent Interface

    Fourth, the generic extension methods

    Extension methods in essence is a static method, so they can write generic

    extension, simple two examples.

    public static T ChangeTo(this object @this)

     {

     var value = default(T);

     value = (T)Convert.ChangeType(@this, typeof (T));

     return value;

     }

     var numberString = 2.ChangeTo();

     var numberBool = 2.ChangeTo();

    Case 2

    public static TValue GetOrAdd(this IDictionary me, TKey key,

    Func constructor)

     {

     TValue value;

     if (me.TryGetValue(key, out value))

     {

     return value;

     }

     value = constructor();

     me.Add(key, value);

     return value;

     }

     var books = new Dictionary();

     var book = books.GetOrAdd(1, () => "book1");

     var book2 = books.GetOrAdd(1, () => "book1");

    Such extension method can make the code more concise.

    Five, a new kind of object-oriented design

    If the scenario above represent only the code level of skills, the following skills is reflected in extension methods in object-oriented, a new design scheme.

    Scene: a motorcycle and a bicycle.Honking (Whistle) and read (ReadSpeed) with the same implementation, real-time speed and braking (Brake) and acceleration (AddSpeed), each has different ways of implementation. According to the scenario we can design the inheritance hierarchy immediately:

    In order to extract honking (Whistle) and read the real-time speed (ReadSpeed) this two behaviors and utilities, we abstract the a Vehicle as an abstract class.This design may be correct, but as an experienced OO developers may not agree with this plan immediately.The reason has 3:

    1. Immediately for common code design class inheritance is not

    convincing, especially early in the design, the abstraction of the

    Vehicle is not necessarily accurate, many public behavior over time

    on the Vehicle in violation of the SRP (single responsibility),

    further breach of OCP (open closed principle)

    2. Object-oriented programming has a guiding principle is called: use

    combination instead of inheritance.This principle tells us that the

    combination is more flexible than inheritance, the possibility that

    don't use inheritance.

    3. Only very sure inheritance, and inheritance relationships in line

    with the LSP (substitution principle on the Richter scale), not to

    think that this abstract class design is no problem.

    Using the method of extension scheme is as follows: abstract interface ICanRun, used to implement the Brake (Brake) and speed (AddSpped).Honking (Whistle) and read the real-time speed (ReadSpeed) two public on the implementation of the extension in the ICanRun interface, the whole implementation is very loose coupling.

internal interface ICanRun

     {

     void Brake();

     void AddSpeed();

     }

     internal class Bicycle : ICanRun

     {

     public void Brake()

     {

     }

     public void AddSpeed()

     {

     }

     }

     internal class Motor : ICanRun

     {

     public void Brake()

     {

     }

     public void AddSpeed()

     {

     }

     }

     internal static class VehicleState

     {

     internal static void Whistle(this ICanRun @this)

     {

     }

     internal static void ReadSpeed(this ICanRun @this)

     {

     }

     }

    Six: summarize

    Now we see the definition of extension methods: Microsoft extension method enables you to "add" approach to the existing type, without having to create new derived types, recompile or modifying the original type in other ways.Here the "add" to use quotation marks because doesn't really add methods to a specified type.

    This definition is more on the extension method is implemented, and the use of this article is to extend methods scene made a summary.The examples in this article can only be the tip of the iceberg in application of extension method.By reading more good code, the intention of the understanding when using extension method enables you to write more concise, more expressive code.

Report this document

For any questions or suggestions please email
cust-service@docsford.com