I have a piece of code like the following:
public class ActivityHelper
{
public void SetDate(IList<Activity> anActivityList)
{
foreach(Activity current in anActivityList)
{
current.Date = DateTime.Now;
}
}
//More methods, properties, fields, etc...
}
This could easily be converted to an extension method. For example:
public static void SetDate(this IList<Activity> aList)
{
foreach(Activity current in anActivityList)
{
current.Date = DateTime.Now;
}
}
The original function doesn't use any instance specific data or methods from the ActivityHelper class which makes it seem like it is in the incorrect place. Is this the correct time to write an extension method? What are the correct scenarios in which to create extension methods?
Brad Adams has written about extension method design guidelines:
CONSIDER using extension methods in any of the following scenarios:
To provide helper functionality relevant to every implementation of an interface, if said functionality can be written in terms of the core interface. This is because concrete implementations cannot otherwise be assigned to interfaces. For example, the LINQ to Objects operators are implemented as extension methods for all IEnumerable types. Thus, any IEnumerable<> implementation is automatically LINQ-enabled.
When an instance method would introduce a dependency on some type, but such a dependency would break dependency management rules. For example, a dependency from String to System.Uri is probably not desirable, and so String.ToUri() instance method returning System.Uri would be the wrong design from a dependency management perspective. A static extension method Uri.ToUri(this string str) returning System.Uri would be a much better design.
I think Extension methods are only appropriate if there is a compelling reason to make the method an extension method.
If the type is one you do not control, and the method should appear to be integral to the type, or if there is a compelling reason to not put the method directly on the type (such as creating an unwanted dependency) then an extension method could be appropriate.
Personally, if the expectation of the user of your API will already be to use the "ActivityHelper" class when working with collections of Activities, then I would probably not create an extension method for this. A standard, non-extension method will actually be a simpler API, since it's easily understood and discoverable. Extension methods are tricky from a usage standpoint - you're calling a method that "looks like" it exists somewhere other than where it actually exists. While this can simplify syntax, it reduces maintainability and discoverability.
In my experience extension methods work best when they:
Don't have side-effects (most of the extension methods my team wrote that have side-effects, we ended up removing because they caused more problems than they helped)
Offer functionality that applies to every possible instance or value of the type they're extending. (Again citing an example from my team, string.NormalizeUrl() is not appropriate because not all strings are even URLs anyway)
Well i usually create extension methods to help me write codes which have a smooth flow. Its generally depends upon the method you are creating.
If you feel that the method should have already been in framework and is too general then its okay to create an extension method for that.
But you need to first analyze that the class you are extending will always will be in state that your extension method can handle.
For Guidelines here to Brad's Article
http://blogs.msdn.com/b/brada/archive/2009/01/12/framework-design-guidelines-extension-methods.aspx
In essence, Extension Methods provide a more fluent style syntax for Helper methods. This translates into the ability to seemingly add functionality to types or all implementations of interfaces.
However, I generally steer away from declaring Extension Methods with a void returntype, as I feel the usefulness of this fluent style syntax, which allows you to compose statements, is negated when the method in question doesn't return anything.
However, I guess it can be handy to have your methods picked up by IntelliSense... :-)
Related
Just getting my feet wet with extension methods and am currently developing some mapping logic to convert an application Invoice to a Quickbooks Invoice. Thought it might be a good idea to have .Convert() extension method.
public static QBInvoice Convert(this InvoiceHeader importedInvoice)
The conversion is just field mapping of one class to another. But then I read somewhere that an extension method is to extend the original class, not convert it to another. Hence why I am asking. I know technically I can do it, but is it best practice compliant or taboo?
Personally I like to use explicit casts so:
public class InvoiceHeader
{
public static explicit operator QBInvoice(InvoiceHeader invoice)
{
return new QBInvoice {}; // do your mapping
}
}
Then you can just cast it:
var qbInvoice = (QBInvoice) invoiceHeader;
we use it to map classes all the time... probably not the best solution but at least you hide boring unnecessary code somewhere far away and make the code that matters (your business logic) nice and readable.
I must strongly disagree with Blogbeard's comment above: mapping between classes has nothing to do with the class itself (SRP) so putting that code outside either of the two classes is way cleaner solution.
A great well-accepted conversion method for classes, defined as an extension method is ToArray(). AsEnumerable, ToList, and ToDictionary are other well-accepted "conversion" extension methods.
"To" or "As" seem to be acceptable naming conventions for extension methods which convert to another type, just as "On" is part of a standard naming convention for events.
I was trying NBuilder in my unit test. An excellent library. However, I could not explain the following structure of classes and interfaces.
In FizzWare.NBuilder namespace:
ISingleObjectBuilder
SingleObjectBuilderExtensions
In FizzWare.NBuilder.Implementation
IObjectBuilder`
ObjectBuilder
SingleObjectBuilderExtensions is simply a wrapper on IObjectBuilder.
The client code should usually use a class named Builder which has a static method that gives you ISingleObjectBuilder. You never need to instantiate any of the classes in client code.
Now, I dont get the point of the SingleObjectBuilderExtensions. Does it give any kind of design benefit? Why not the methods are directly in ISingleObjectBuilder specially when the two interfaces are in same namespace.
ISingleObjectBuilder is an interface; interfaces cannot provide implementation. That would mean that every implementation of ISingleObjectBuilder would need to provide the implementation.
However, in many cases, a method has a pre-defined behaviour, and just needs access to other members of the interface (i.e. just members of ISingleObjectBuilder), so there is no benefit in making each implementation provide this.
Additionally, it is not a good idea to add more members to an existing interface, since that would be a breaking change for all existing implementations.
Extension methods solve both of these issues:
the extension method will work for all implementations of ISingleObjectBuilder
it doesn't change the existing API, so all existing implementations will continue to be valid
Having it in the same namespace simply makes it convenient. It is a likely bet that any code using ISingleObjectBuilder already has a using directive importing that namespace; therefore, most code will already see the extension method in the IDE simply by pressing . in the IDE.
To add a concrete example, LINQ-to-Objects works on IEnumerable<T>. There are lots of IEnumerable<T> implementations. If each of them had to write their own First(...), FirstOrDefault(...), Any(...), Select(...) etc methods, that would be a huge burden - bot would provide no benefit as the implementations would be pretty much identical in most cases. Additionally, fitting this onto the interface retrospectively would have been disastrous.
As a side note: per-type versions of a method always take precedence over extension methods, so if (in the case of LINQ-to-Objects) you have a type that implements IEnumerable<T> (for some T), and that type has a .First() instance method, then:
YourType foo = ...
var first = foo.First();
will use your version, not the extension methods.
Extension methods are only syntactic sugar. They are normal static methods that work with public data the class they "extend" exposes.
There doesn't seem to be need for those extension methods to work with private fields and it also gives you ability to have interface instead of abstract class. And everyone knows interfaces are better choice than abstract classes.
And the reason for both to be in same namespace is to avoid declaring new namespace just to use the extension methods. How many times did it happen to you, that you tried to use LINQ only to notice there are no methods in intellisense or the code didn't compile. Reason being there was not System.Linq namespace included.
Before you start pointing me to duplicates just know that I have read nearly all the posts on SO about extension methods. I am just trying to play devil's advocate for a minute to consider the alternative to my working opinion.
Recently I was working on a project and a need came up for a method to be a base of an interface. So I suggested we write an extension method and it was shot down. Saying it added complexity and harder to debug.
I of course argued and got on SO to find all the wonderful posts that show the many reasons why to use extension methods. Not to forget that a lot of the .net framework uses them. We eventually did not use it as I was overruled by the team.
But then it got me thinking, are there times when an extension method could be used but shouldn't be?
I really couldn't think of any but thought I would post here and see if anyone could think of any other reasons why they shouldn't be used.
Any time you have a function which is "generally applicable" to an object of a certain type, regardless of its state, an extension method is a good choice.
For example, today I added two new extension methods to our codebase:
public static XElement ToXElement(this XmlElement element) { }
public static XmlElement ToXmlElement(this XElement element) { }
Both of these are, generally speaking, valid on the types they extend regardless of the state of the instance or where we are using it.
If your method does not meet that criteria, it should probably be moved to a helper method closer to the context where the particular case is always true or easily checked.
For example, a developer recently nominated this to be an extension method:
public static bool ParseYesNoBool(this string input) { }
There are two problems here: first, this will appear on all strings in the application, even though the number of strings which might ever be candidates for this case are very small. So we've broken the first rule, in that it is not useful regardless of state. Similarly, but second, the consumer of this functionality is limited to a single parser for one particular connector to an external system. So promoting implementation-specific functionality into the general-use namespace makes no sense. This was downgraded to a helper method in the parser.
As far as readability and debugging, that is just incorrect for a developer of any reasonable skill level.
In general if you control the source-code for the assembly and adding the method does not cause any breaking changes to existing code (which would have been the case if for example LINQ had not been implemented via extension methods) it is better to just add a normal method.
This discussion of the Framework Design Guildelines section on extension methods contains some good advice. I think the relevant portion for your scenario is:
To provide helper functionality relevant to every implementation of an interface, if said functionality can be written in terms of the core interface.
If your proposed usage did not pass that test then it should have been shot down.
I would say you should avoid them when "they do not make the intend of the code more clear". Of course, whether or not some code (or codeing style) is "more clear" varying widely between people, so that's pretty much useless. (I had one boss who said we shoudl avoid using interfaces because they made the code "too complex and hard to understand")
Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type.
Any time you break the intent and design for the feature I would recommend reconsidering the use of an extension method. I see a few situations when you don't want to use an Extension method:
1) Changing the Object Model to allow for an Extension method: The class you want to create an extension on is an abstract class. This is going to require you either make each inherited class it's own version of the extension or remove abstract from the class. Either way, you are changing the object model in order to use an extension method.
2) Forgetting the Decorator Pattern: The number of extension methods you create for a class exceeds three. I find it is easier to organize/communicate and maintain the domain/object model with decorated objects than with extended objects. However, the opposite is also true: If a decorated object has less than four methods, I find a lot of almost "empty" objects in my project.
3) Private functions: Private functions are meant to modify(create, delete, etc..) the object and extension methods are meant to use the type, much like a struct would. If you find the extension is being assigned to another instance of the type then it probably should not be in an extension.
I have created an extension method for an ASP.NET MVC ViewPage, e.g:
public static class ViewExtensions
{
public static string Method<T>(this ViewPage<T> page) where T : class
{
return "something";
}
}
When calling this method from a View (deriving from ViewPage), I get the error "CS0103: The name 'Method' does not exist in the current context" unless I use the this keyword to call it:
<%: Method() %> <!-- gives error CS0103 -->
<%: this.Method() %> <!-- works -->
Why is the this keyword required? Or does it work without it, but I'm missing something?
(I think there must be a duplicate of this question, but I was not able find one)
Update:
As Ben Robinson says, the syntax to call extension methods is just compiler sugar. Then why can't the compiler automatically check the for extension methods of the current type's base types without requiring the this keyword?
A couple points:
First off, the proposed feature (implicit "this." on an extension method call) is unnecessary. Extension methods were necessary for LINQ query comprehensions to work the way we wanted; the receiver is always stated in the query so it is not necessary to support implicit this to make LINQ work.
Second, the feature works against the more general design of extension methods: namely, that extension methods allow you to extend a type that you cannot extend yourself, either because it is an interface and you don't know the implementation, or because you do know the implementation but do not have the source code.
If you are in the scenario where you are using an extension method for a type within that type then you do have access to the source code. Why are you using an extension method in the first place then? You can write an instance method yourself if you have access to the source code of the extended type, and then you don't have to use an extension method at all! Your implementation can then take advantage of having access to the private state of the object, which extension methods cannot.
Making it easier to use extension methods from within a type that you have access to is encouraging the use of extension methods over instance methods. Extension methods are great, but it is usually better to use an instance method if you have one.
Given those two points, the burden no longer falls on the language designer to explain why the feature does not exist. It now falls on you to explain why it should. Features have enormous costs associated with them. This feature is not necessary and works against the stated design goals of extension methods; why should we take on the cost of implementing it? Explain what compelling, important scenario is enabled by this feature and we'll consider implementing it in the future. I don't see any compelling, important scenario that justifies it, but perhaps there is one that I've missed.
Without it the compiler just sees it as a static method in a static class which takes page as it's first parameter. i.e.
// without 'this'
string s = ViewExtensions.Method(page);
vs.
// with 'this'
string s = page.Method();
On instance methods, 'this' is implicitly passed to each method transparently, so you can access all the members it provides.
Extension methods are static. By calling Method() rather than this.Method() or Method(this), you're not telling the compiler what to pass to the method.
You might say 'why doesn't it just realise what the calling object is and pass that as a parameter?'
The answer is that extension methods are static and can be called from a static context, where there is no 'this'.
I guess they could check for that during compilation, but to be honest, it's probably a lot of work for extremely little payoff. And to be honest, I see little benefit in taking away some of the explicitness of extension method calls. The fact that they can be mistaken for instance methods means that they can be quite unintuitive at times (NullReferenceExceptions not being thrown for example). I sometimes think that they should have introduced a new 'pipe-forward' style operator for extension methods.
It's important to note that there are differences between extension methods and regular methods. I think you've just come across one of them.
I'll give you an example of another difference: It's fairly easy to call an extension method on a null object reference. Fortunately, this is much more difficult to do with regular methods. (But it can be done. IIRC, Jon Skeet demonstrated how to do this by manipulating CIL code.)
static void ExtensionMethod(this object obj) { ... }
object nullObj = null;
nullObj.ExtensionMethod(); // will succeed without a NullReferenceException!
That being said, I agree that it seems a little unlogical that this is required to call the extension method. After all, an extension method should ideally "feel" and behave just like a normal one.
But in reality, extension methods are more like syntactic sugar added on top of the existing language than an early core feature that fits nicely into the language in all respects.
Because the extension method does not exist with the ViewPage class. You need to tell the compiler what you are calling the extension method on. Remember this.Method() is just compiler sugar for ViewExtensions.Method(this). It is the same way you can't just call an extention method within the middle of any class by the method name.
I am working on a fluent API and ran into the same issue. Even though I have access to the class I'm extending I still wanted the logic of each of the fluent methods to be in their own files. The "this" keyword was very unintuitive, users kept thinking the method was missing. What I did was make my class a partial class that implemented the methods I needed instead of using extension methods. I saw no mention of partials in the answers. If you have this question partials might be a better option.
I recently asked this question:
Compiler error referencing custom C# extension method
Marc Gravell answer was perfect and it solved my problem. But it gave me something to think about...
If and Extension method must be placed on a Static Class and the method itself must be static, why can't we create a static Extension method?
I understand that the parameter marked as "this" will be used to allow access to an instance of the object we are extending. What I do not understand is why can't a method be created to be static... it just seems to me that this is a senseless limitation...
My question is: Why can't we create an extension method that will work as a static Method?
I expect the real answer is simply: there wasn't a good use-case. For instances, the advantage is that it enables a fluent-API over existing types (that don't themselves provide the logic) - i.e.
var foo = data.Where(x=>x.IsActive).OrderBy(x=>x.Price).First();
which enables LINQ:
var foo = (from x in data
where x.IsActive
order by x.Price
select x).First();
With static methods, this simply isn't an issue, so there is no justification; just use the static method on the second type.
As it is, extension methods are not properly object orientated - they are a pragmatic abuse to make life easier at the expense of purity. There was no reason to dilute static methods in the same way.
Because that feature doesn't exist in C#.
As a workaround, static methods can be implemented in another class and called through that class to provide the added functionality.
For example, XNA has a MathHelper class which ideally would have been static extensions to the Math class.
The community is asking if we think it's a good idea for C# 4.0
My thinking would be for compatibility - if you suddenly made all static methods extension methods with the need for the this operator you could inadvertently break code which now is overriding a normal method with an extension method.
The this parameter allows control and thus doesn't break compatibility.
Just an idea though.
First of all you would have to add yet another syntax to indicate you want to extend the static methods of the existing type. When extending syntax you really need a very good reason to do so.
Lets imagine I have a class called MyExts which allow me to add extension methods to MyClass. Why would:-
MyClass.DoSomethingExtra();
be better than
MyExts.DoSomethingExtra();
?