Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extension Methods vs Instance Methods vs Static Class [closed]

I'm a little bit confused about the different ways to use methods to interact with objects in C#, particularly the major design differences and consequences between the following:

  1. Invoking an instance method
  2. Using a static class on a POCO
  3. Creating an extension method

Example:

public class MyPoint
{
    public double x { get; set; }
    public double y { get; set; }

    public double? DistanceFrom(MyPoint p)
    {
        if (p != null)
        {
            return  Math.Sqrt(Math.Pow(this.x - p.x, 2) + Math.Pow(this.y - p.y, 2));
        }
        return null;
    }
}

If you could accomplish the desired outcome by simply placing a method in a class definition, why would a POCO combined with either a static helper class or an extension method be preferable?

like image 688
johnnyRose Avatar asked May 29 '15 18:05

johnnyRose


People also ask

What is the difference between a static method and an extension method?

The only difference between a regular static method and an extension method is that the first parameter of the extension method specifies the type that it is going to operator on, preceded by the this keyword.

Can we use extension method in sealed class?

The main advantage of the extension method is to add new methods in the existing class without using inheritance. You can add new methods in the existing class without modifying the source code of the existing class. It can also work with sealed class.

Are extension methods static?

Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type." Essentially, an extension method is a special type of a static method and enable you to add functionality to an existing type even if you don't have access to the source code of the type.

What is the difference between static class method and instance method?

Instance method are methods which require an object of its class to be created before it can be called. Static methods are the methods in Java that can be called without creating an object of class.


1 Answers

You asked, "If you could accomplish the desired outcome by simply placing a method in a class definition, why would a POCO combined with either a static helper class or an extension method be preferable?"

The answer is that it depends on the situation, and if the methods in question are directly related to your class' primary concern (see single responsibility principle).

Here are some examples of where it might be a good idea to use each type of approach/method (using your code sample as a starting point).

1. Instance Methods

//This all makes sense as instance methods because you're 
//encapsulating logic MyPoint is concerned with.
public class MyPoint
{
    public double x { get; set; }
    public double y { get; set; }

    public double? DistanceFrom(MyPoint p)
    {
        if (p != null)
            return  Math.Sqrt(Math.Pow(this.x - p.x, 2) + Math.Pow(this.y - p.y, 2));            
        return null;
    }
}

2. Static Class Methods - An error logging example.

    //Your class doesn't directly concern itself with logging implmentation;
    //that's something that is better left to a separate class, perhaps
    //a "Logger" utility class with static methods that are available to your class.
    public double? DistanceFrom(MyPoint p)
    {
        try
        {
            if (p != null)
                return  Math.Sqrt(Math.Pow(this.x - p.x, 2) + Math.Pow(this.y - p.y, 2));            
            return null;
        }
        catch(Exception ex)
        {
             //**** Static helper class that can be called from other classes ****
             Logger.LogError(ex);

             //NOTE: Logger might encapsulate other logging methods like...
             //Logger.LogInformation(string s)
             //...so an extension method would be less natural, since Logger
             //doesn't relate to a specific base type that you can create an
             //extension method for.
        }
}

3. Extension Methods - An XML serialization example.

//Maybe you want to make it so that any object can XML serialize itself
//using an easy-to-use, shared syntax.
//Your MyPoint class isn't directly concerned about XML serialization,
//so it doesn't make sense to implement this as an instance method but
//MyPoint can pick up this capability from this extension method.
public static class XmlSerialization
{
    public static string ToXml(this object valueToSerialize)
    {
        var serializer = new XmlSerializer(valueToSerialize.GetType());
        var sb = new StringBuilder();
        using (var writer = new StringWriter(sb))
            serializer.Serialize(writer, valueToSerialize);

        return sb.ToString();
    }
}

//example usage
var point = new MyPoint();
var pointXml = point.ToXml(); //<- from the extension method

The rule of thumb is:

  1. If the method relates to a class' primary concern, put it in an instance method.
  2. If you have a generic utility that might be useful to multiple classes, consider putting it in a static class' method.
  3. If you have a situation similar to 2, but related to a single base type, or you think the code would look cleaner/more concise without having to separately reference a static class, consider an extension method.
like image 81
Colin Avatar answered Sep 18 '22 05:09

Colin