Tuesday, April 19, 2011

Can extension methods on your own types make sense?

The visceral reaction - "of course not". If you are the owner of the source code, why on earth would you need to define extension methods on types that, literally by definition, you have complete control of?

But as I discovered some time ago, this is too naive a view. In my case, dependencies led me to define an extension to one of my own abstractions. Simply put, Assembly A, defines an object A' that exposes basic conversion operators over the Object type, and has as state a weakly typed Object property (in this example, a mechanism that allows arbitrary properties to be attached to a domain object - not as part of an interface, but as state that may be used by an integration approach). Assembly B, which references Assembly A, defines abstractions (say, B') that may be housed in an instance of A' via appeal to an integral type and would like conversion operators to be available - well, in this case, not operators, as they are statically defined, but at least methods that would save repetition.

Providing a conversion method in A' leads to a circular dependency. So there are two options; provide some static method in Assembly B to define a conversion, or create an extension method on A' in Assembly B that understands about the type B'. Such an extension is shown below, with A' == AttachedProperty and B' == IFiscalQuantity.

   public static class AttachedPropertyExtensions {  
     public static IFiscalQuantity AsFiscalQuantity(this AttachedProperty pProperty) {  
       return DomainObjectFactory.Instance.CreateObject<IFiscalQuantity>((decimal)pProperty);  
     }  
   }  

No comments: