A contractor where I work is using extension methods
to implement CRUD
on well-known internal classes that we own. I say it is better to use normal inheritance
over extension methods
for the following reasons.
CRUD
methods.extension methods
make heavy use of reflection
(which is slower).His logic is, "It's compiled, so it's fast." Maybe I'm wrong...but just because it is compiled doesn't mean it doesn't use reflection, nor does it mean it is faster than normal inheritance.
So my questions are:
extension methods
work under-the-hood?inheritance
or extension methods
on WELL-KNOWN classes that you OWN?Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are static methods, but they're called as if they were instance methods on the extended type.
The main advantage of the extension method is to add new methods in the existing class without using inheritance. You can add new methods in the existing class without modifying the source code of the existing class. It can also work with sealed class.
For an application programmer, extension methods are an incredibly powerful and expressive tool. They enable convenience, extensibility, and an improved intellisence experience. However, many of the features that make extension methods so useful for library consumers can be problematic for class library authors.
How do extension methods work under-the-hood?
They're just static methods; the compiler rewrites calls like myObject.MyExtensionMethod()
to MyExtensionClass.MyExtensionMethod(myObject)
.
Is it better to use inheretance or extension methods on WELL-KNOWN classes that you OWN?
There's not single answer to this question, it all depends on the context. But usually extension methods are most useful in those cases:
IEnumerable<T>
and Linq extension methods)I assume extension methods make heavy use of reflection (which is slower).
No. Extension methods are resolved at compile-time, no reflection required.
That negates your performance concerns.
Is it better to use inheretance or extension methods ?
I would say neither. Use a Repository (DAL). An entity should be persistence-agnostic (so: no inheritance from a base that does CRUD) and not pretend to be involved where it's not (no extensions).
You are right that "Using extension methods obfuscates & confuses the source of the CRUD methods" but inheritance is not the 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