Tutorial :Do extension methods violate software engineering principles?



Question:

I tend to shy away from extension methods (in C# ), as it violates 'code cohesion' principle of software engineering.

Then, why is it there? or is my understanding wrong?


Solution:1

On the contrary, I believe judicious use of extension methods improves code cohesion, as you can put methods and classes doing related tasks together. The situation is no different from free (static) methods and Koenig lookup in C++, extension access with . is merely syntactic sugar.


Solution:2

Extension methods are like any tool in your arsenal. When used wisely, they are a powerful addition and enable you to write things that would be clumsy to express otherwise. Used poorly, they're an awkward crutch to stitch things together.

That said, I disagree with your statement that it violates code cohesion -- I think it's actually quite the opposite. If you didn't have extension methods, you'd be forced to use utility classes scattered everywhere throughout your code.


Solution:3

I don't think extension methods violate code cohesion any more than a group of static methods do. Because at their core extension methods are just a group of static methods. The C# and VB.Net compiler just provide a nice friendly syntax for them.

People have been creating static utility methods for classes they don't control for quite some time and they fit into well established engineering practices.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »