One interesting aspect of extension methods in .NET is the fact that you can apply them to interfaces. For me, it seems nice that I can define functionality near the interface without defining an abstract class that clutters the assembly.
I know that abstract classes are not obsolete or anything, but how do you feel about utilizing this side effect in your code?
Example:
public static class IUserExtensions
{
public static bool IsCurrentUser(this IUser user)
{
return (HttpContext.Current.User != null &&
HttpContext.Current.User.Identity.Name == user.ID.ToString());
}
}
public interface IUser {
int ID { get; set; }
}
The problem here is not that you can't add an extension method to an abstract class (you can - you can add an extension method to any type) - it's that you can't add a static method to a type with extension methods. Extension methods are static methods that present themselves in C# as instance methods.
An abstract class is a good choice if you have plans for future expansion – i.e. if a future expansion is likely in the class hierarchy. If you would like to provide support for future expansion when using interfaces, you'll need to extend the interface and create a new one.
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.
Extension methods are an excellent addition to the C# language. They enable us to write nicer, more readable code. They allow for more functionally styled programming, which is very much needed in an object-oriented language. They also should be used with care.
What extension methods lets you do is to focus in on what abstract classes should actually be doing. There's a temptation to implement "utility" code in abstract classes because it will be used by implementers even though it may not be part of the logical inheritance tree. Extension methods let you attach these utility methods to the interface without cluttering up your abstract base classes.
EDIT
Specifically, I would apply these guidelines.
Inheritance
Utility Classes
Extension Methods
EDIT 2
Thought of another DO for extension methods
DO use extension methods to provide a natural language (internal DSL) for certain implementations. Here's a silly example.
int age = getAge();
if (age.IsDraftAge() && !age.IsLegalDrinkingAge())
{
Console.WriteLine(@"You cannot drink until your birthdate on {0}.
Join the army instead.",
age.GetYearWhenGettingDrunkIsOk());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With