The new extensions in .Net 3.5 allow functionality to be split out from interfaces.
For instance in .Net 2.0
public interface IHaveChildren {
string ParentType { get; }
int ParentId { get; }
List<IChild> GetChildren()
}
Can (in 3.5) become:
public interface IHaveChildren {
string ParentType { get; }
int ParentId { get; }
}
public static class HaveChildrenExtension {
public static List<IChild> GetChildren( this IHaveChildren ) {
//logic to get children by parent type and id
//shared for all classes implementing IHaveChildren
}
}
This seems to me to be a better mechanism for many interfaces. They no longer need an abstract base to share this code, and functionally the code works the same. This could make the code more maintainable and easier to test.
The only disadvantage being that an abstract bases implementation can be virtual, but can that be worked around (would an instance method hide an extension method with the same name? would it be confusing code to do so?)
Any other reasons not to regularly use this pattern?
Clarification:
Yeah, I see the tendency with extension methods is to end up with them everywhere. I'd be particularly careful having any on .Net value types without a great deal of peer review (I think the only one we have on a string is a .SplitToDictionary()
- similar to .Split()
but taking a key-value delimiter too)
I think there's a whole best practice debate there ;-)
(Incidentally: DannySmurf, your PM sounds scary.)
I'm specifically asking here about using extension methods where previously we had interface methods.
I'm trying to avoid lots of levels of abstract base classes - the classes implementing these models mostly already have base classes. I think this model could be more maintainable and less overly-coupled than adding further object hierarchies.
Is this what MS has done to IEnumerable and IQueryable for Linq?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…