views:

154

answers:

3

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?

+8  A: 

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.

Anton Tykhyy
+1, Exactly. It is syntactic sugar on a static method, and that's how it should be used as.
Stefan Steinegger
+6  A: 

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.

John Feminella
A: 

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.

JaredPar