I've been thinking about using extension methods as a replacement for an abstract base class. The extension methods can provide default functionality, and can be 'overridden' by putting a method of the same signature in a derived class.
Any reason I shouldn't do this?
Also, if I have two extension methods with the same signature, which one is used? Is there a way of establishing priority?
You can use extension methods to extend a class or interface, but not to override them. An extension method with the same name and signature as an interface or class method will never be called.
It is not possible, for example, to override the existing functionality of a class using an extension and extensions cannot contain stored properties.
In C#, the extension method concept allows you to add new methods in the existing class or in the structure without modifying the source code of the original type and you do not require any kind of special permission from the original type and there is no need to re-compile the original type.
In Java you add extension methods via Manifold, a jar file you add to your project's classpath. Similar to C# a Java extension method is declared static in an @Extension class where the first argument has the same type as the extended class and is annotated with @This .
In general, you shouldn't provide "base" functionality through extension methods. They should only be used to "extend" class functionality. If you have access to the base class code, and the functionality you're trying to implement is logically part of the inheritance heirarchy, then you should put it in the abstract class.
My point is, just because you can doesn't mean you should. It's often best just to stick with good old fashioned OOP and use the newer language features when plain old OO programming falls short of providing you a reasonable solution.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With