Sponsored By Aspose - File Format APIs for .NET

Aspose are the market leader of .NET APIs for file business formats – natively work with DOCX, XLSX, PPT, PDF, MSG, MPP, images formats and many more!

Extension Method Best Practices?

Interesting discussion that came up on the ALT.NET list. Many people simply say don’t do that but they have a time and place and should be weighed like any other architectural or API decision. While I find that many people will misuse this feature to extremes and code will quickly become unmaintainable I can understand the possible benefits of them (especially in the context of LINQ).

 

So my #1 best practice for extension methods?

ALL extension methods should be [SIDE EFFECT FREE FUNCTIONS]

I wish that the C# compiler would enforce this rule to not let you create an extension method that was not side effect free but unfortunately this is not the case. Extension methods that change state are quite evil.

 

What do you see as best practices? 

 

This entry was posted in Uncategorized. Bookmark the permalink. Follow any comments here with the RSS feed for this post.

20 Responses to Extension Method Best Practices?

  1. Marden says:

    Hi everyone. It is not enough to succeed. Others must fail. Help me! Looking for sites on: Payday loan. I found only this – frontline Flea and tick. About is your ultimate online destination for discovering the newest and best in style, shopping, and emerging trends from the runways to the streets. If an insect is affected it is unable to reproduce so drug resistant offspring should not be a problem. With best wishes :-(, Marden from Luxembourg.

  2. Rhiannon says:

    Hello everyone. Humor is also a way of saying something serious.
    I am from San and now teach English, tell me right I wrote the following sentence: “The flea is covered in mucus and keeps sliding.More pet owners are reporting what they believe to be harmful side effects from flea and tick treatments.”

    Thank you so much for your future answers :D. Roscoe.

  3. Trent says:

    Hi guys. By prizing heartfulness above faultlessness, we may reap more from our effort because we’re more likely to be changed by it. Help me! Looking for sites on: Teen Lesbian Photo. I found only this – black lesbian. Most emailed this week spend time with your kids, so peyton manning doesn. Goto page next have alot of lesbian movies to see though, that favorite lesbian movie – imagine me you. With best wishes :confused:, Trent from Antigua.

  4. Kitra says:

    Could you help me. After all it is those who have a deep and real inner life who are best able to deal with the irritating details of outer life.
    I am from Cambodia and , too, and now am writing in English, please tell me right I wrote the following sentence: “Your source of celebrity gossip, entertainment news and movie reviews crime drama once fallen, I also play an old lesbian in ed harris next movie.”

    With best wishes 8), Kitra.

  5. Lucinda says:

    Good Day. Good, fuck this webmaster, kiss my ass. Help me! Could you help me find sites on the: Anti-allergic. I found only this – [url=http://genericentocort.info]entocort for colitis[/url]. Has introduced a rx to otc switch product for allergic related rhinitis and skin problems, available from november. Agent allergic rhinitis anti asthmatic drugs already in use should not be withdrawn abruptly at the. Thanks for the help :-(, Lucinda from Sudan.

  6. Aaron says:

    I have heard that extension methods are code obfuscation alot lately, but i have to disagree.

    Say there is a method you wish to add to the DataTable, a method to count all cells. you can
    1) extend it
    2) add a method

    Lets say we want to impress our friends and do it the “right” way. We go ahead a create a new class in inherit the DataTable.
    We take a class everyone knows and loves and transform it into a class no one knows anything about. In actuality, everyone knows what 99% of this class does, they just don’t know they know it because it has been renamed.

    Lets say we want reuseable code and to make it easy for others read. We decide to do it the “wrong” way. We simply add an extension method. People fixing our code will see the datatable and know exactly what it does. When they see that our datatable has extra methods they can go look at the code for that method. They dont need to go through the entire class.

    In short, DataTable.MyExtensionMethod() is far less obfuscated then UnknownClass.MyMethod()

    I can’t wait for the Expando properties coming out in C# 4.0

  7. Hendry Luk says:

    I know it’s an old post, but I think this is a perfect place to ask this question.
    I always think we should avoid extension method in most situation. It is a bad thing the same way static method is bad thing.
    The biggest problem with ext method is that it shares the same problem with static method: testability.
    Probably the only way to mock away an extension method is by using typemock. Many mocking framework designers decide not to provide this bytecode magic feature in their products simply because any code that requires bytecode magic to be tested generally signifies bad code at first place.
    Perhaps with the emergence of ext method, this norm should change?

  8. Greg says:

    Kent I have seen *maybe* 1 use of extension methods that included mutable methods and was actually something that would survive for 10 seconds in a code review … It was making a fluent interface on objects that did not have one …. personally I think this should be done with a facade (and everything becomes more explicit/controlled) but I can understand the desire to do such things. I have not really seen any valid mutable extension methods …. Since the main use of extension methods is also within what is for all intensive purposes functional code it seems to me a good idea to follow well established functional behaviors.

    Cheers,

    Greg

  9. Great post…. my thoughts exactly. I believe that extensions will be grossly over used.

    Give a man a hammer, everything becomes a nail.

  10. So you’re saying if there’s a mutable type with instance methods that perform mutations, if I add an extension method I should do things in an immutable fashion anyway? That sounds crazy to me. Callers of the APIs shouldn’t be able to differentiate between instance / extension method calls – that’s kind of the point of them. Yes, extension methods will be abused by some, but what tool isn’t?

    +1 for spec# / C# convergence!

  11. Greg says:

    Peter.

    Welcome to the group of us who hope spec# makes it into 4.0 :)

  12. I would agree. I believe there’s benefit to mandating that class state be immutable (I’m sure I’ve seen this before but I can’t find reference to it) so it’s not much of a stretch to expect static methods (including extension methods) treat the objects they accept as parameters (or extend) as immutable.

    Extension methods are “special” all-around, and I think they have the propensity to make the programmer forget they’re working with a static method as well as forgetting about good OO design.

    It is very unfortunate that you can’t inject design attributes of a class into its declaration (like declaring that a class is immutable and therefore generate compile warnings on code that does modify state) and I really hope that ability is added to C# 4 (should that ever exist) and also include the ability to declare immutable static classes or immutable static state. Although, I don’t think this would introduce anything to avoid writing side-effect free extension methods…

  13. Greg says:

    A side effect free function is one that does not change the state of the object it is called on … it can however return me a new object. A great (and silly) example of a side effect free function would be …

    DateTime ThirtyDaysFromNow(DateTime Date) {
    return Date.AddDays(30);
    }

    I think that no extension method should ever try to change the state of the object its working on … if it wants to do such a state transition it should be returning me a new object (leaving my original object in its original state) …

    This is a very common pattern in functional programming and the places where extension methods have the most use is in functional situations (linq)…

  14. Tinco says:

    Hey Greg, what state? And why is it bad? Your blog post is a bit too short :)

  15. But the bug question is… why? Extension methods can only hit public properties/metods. So if an extension method changes an object via it’s public properties, hows that different than something else that changes an object through it’s public properties?

  16. Jimmy Bogard says:

    Put them in a namespace such that the client has to “opt-in” to the extension methods. The namespace should only contain the extension method classes and any other classes used by the extension methods. For example, don’t put your favorite “System.String” extension methods (.ToAlternatingCase) in the “System” namespace, put it in “System.String.Extensions” or something similar.

    The namespace should be explicit to both the user writing the code and the user reading the code 6 months later exactly what extensions are being brought in simply by looking at the using statements.

  17. sergiopereira says:

    What kinds of side effects are you suggesting to prohibit? Would you consider changing the target a side-effect?

  18. #1 rule: avoid is possible. Use existing OO techniques to extend types if possible. Extension methods == last resort.
    #2 rule: just like any other code, look for reuse. See if there’s an existing standard library of extension methods that solves your problem.

    One interesting use of extension methods is the one I mention here: http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2412567&SiteID=1. That is, use extension methods to extend enums for purposes such as converting to strings for the UI. However, in the WPF world I would simply use a converter or data template scoped at the application level. It would make more sense for methods unrelated to UI.

    PS. Change state of what? The extension target object? Or global state? The former I don’t see a problem with. The latter makes me shudder.

  19. Mike Chaliy says:

    Most valued one

    Not to use extension methods at all.

    This hack can be needed for API designers. But this is no point to have extension methods in regular code.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>