Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding Extension Methods

Tags:

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?

like image 410
JoshRivers Avatar asked Jan 23 '09 19:01

JoshRivers


People also ask

Can I override extension method?

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.

Can we override methods in extension in Swift?

It is not possible, for example, to override the existing functionality of a class using an extension and extensions cannot contain stored properties.

What are extension methods in C#?

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.

Are there extension methods in Java?

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 .


1 Answers

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.

like image 168
Michael Meadows Avatar answered Sep 30 '22 17:09

Michael Meadows