79741589

Date: 2025-08-20 21:11:46
Score: 0.5
Natty:
Report link

I've written the occasional extension method in situations where it seemed to make sense, and I absolutely love what you can do with Linq, but I think there's one major drawback to the overuse of extension methods that no one else here has mentioned.

They can be a nightmare for Unit Testing, as they can severely complicate the process of Mocking public interfaces.

Numerous times now, I've approached writing a unit test that seems like it will be pretty straight forward. The method I'm testing has a dependency on an external service (ISomeService) and is calling the .Foo() method on that service.

So I create a mock ISomeService object using Moq or any other mocking framework, and go ahead and attempt to mock the Foo() call, only to discover that Foo() is an extension method. So now I have to dig into third party extension method code to try and figure out what actual member of the ISomeService interface is being ultimately being called by the Foo() extension method. And maybe Foo() calls Foo(int, string) which is also an extension method and that calls Foo(int, string, SomeEnumType, object[]), and on and on it goes until eventually I find where its actually calling a method that's actually a member of an the ISomeService interface.

And that's if I'm lucky enough to find that my original Foo() call ultimately maps to just one invocation on the actual interface. If I'm unlucky, I may dig through a tangled web of third party extension method code to ultimately find calls to ISomeService.Bar(), ISomeService.Blam(string, bool), ISomeService.Fizzle(object[]), and ISomeService.Whomp(IEumerable<Task<bool>>). And now I need to figure out how to mock all those invocations just to adequately mock my one simple call to the Foo() extension method.

And that's not even the worst case scenario. Sometimes that tangled web of extension methods ends up referencing and passing around instances of types that are internal to those third party libraries, so I don't even have access to directly reference the types in my mocks. And all this time I'm screaming in my head, "Did you REALLY need to put all this stuff in extension methods??? Just make Foo() part of the interface!"

So, I would say if you're working on library code that's meant to be consumed by third parties, have mercy on those of us who just want to write good, well-tested code and use extension methods sparingly.

Reasons:
  • Blacklisted phrase (0.5): I need
  • Blacklisted phrase (1): ???
  • Long answer (-1):
  • No code block (0.5):
  • Contains question mark (0.5):
  • High reputation (-1):
Posted by: jkindwall