Greg Young [MVP]

Sponsors

The Lounge

News

Advertisement

Images in this post missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at imagehelp@codebetter.com
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? 

 


Posted 11-19-2007 1:37 AM by Greg

[Advertisement]

Comments

Mike Chaliy wrote re: Extension Method Best Practices?
on 11-19-2007 3:57 AM

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.

Kent Boogaart wrote re: Extension Method Best Practices?
on 11-19-2007 7:50 AM

#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: forums.microsoft.com/.../ShowPost.aspx. 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.

Daily Dose of Links - 20071119 « Daily Geek Bits wrote Daily Dose of Links - 20071119 « Daily Geek Bits
on 11-19-2007 8:50 AM

Pingback from  Daily Dose of Links - 20071119 « Daily Geek Bits

sergiopereira wrote re: Extension Method Best Practices?
on 11-19-2007 9:17 AM

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

Jimmy Bogard wrote re: Extension Method Best Practices?
on 11-19-2007 9:40 AM

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.

Aaron Erickson wrote re: Extension Method Best Practices?
on 11-19-2007 9:52 AM

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?

Tinco wrote re: Extension Method Best Practices?
on 11-19-2007 12:12 PM
Hey Greg, what state? And why is it bad? Your blog post is a bit too short :)
Greg wrote re: Extension Method Best Practices?
on 11-20-2007 1:38 PM

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)...

Peter Ritchie wrote re: Extension Method Best Practices?
on 11-20-2007 3:29 PM
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...
Greg wrote re: Extension Method Best Practices?
on 11-20-2007 3:32 PM

Peter.

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

Kent Boogaart wrote re: Extension Method Best Practices?
on 11-21-2007 4:14 AM
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!
Derik Whittaker wrote re: Extension Method Best Practices?
on 11-21-2007 9:05 AM

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

Give a man a hammer, everything becomes a nail.

Greg wrote re: Extension Method Best Practices?
on 11-21-2007 12:00 PM

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

Aaron wrote re: Extension Method Best Practices?
on 12-08-2008 7:02 PM
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

Add a Comment

(required)  
(optional)
(required)  
Remember Me?