1

We strictly adhere to inversion of control in our codebase, but that creates hellish constructors (yes, I know that means our classes aren't cohesive enough, this is a work in progress).
The thing is, that sometimes those dependencies are quite silly like a DateTime wrapper to enable date mocking, or the logger, or a TaskFactory wrapper which are not directly related to the business of the class and I do not think they require explicit introduction.

Could we ease the load on our ctors by using a service locator for those items which are passed all over the system? What would be the disadvantages?

Ziv
  • 2,625
  • 4
  • 26
  • 42
  • Why do you use date mocking, a taskfactory wrapper etc? Just interested. – jgauffin Dec 16 '15 at 15:31
  • Date mocking for testing, a task wrapper is someone's idea of being smart. But it would make it easier to test the classes that deal with threading. – Ziv Dec 16 '15 at 15:32
  • Date testing can be done by proximity. For instance: `DateTime.Now.Substract(entityBeingTested.CreatedAt).TotalMilliseconds < 10`. Testing threading is a pain. The easiest approach is to test the actual code that runs instead. – jgauffin Dec 16 '15 at 15:42
  • Your approach doesn't help me if I want to fast forward time. About testing threading, you shouldn't test that threading is working, but it allows you to make sure a certain class is starting X amount of tasks. Also, it allows you for example to cancel all asynchronicity in the program for testing or debugging. – Ziv Dec 16 '15 at 17:57

1 Answers1

4

Could we ease the load on our ctors by using a service locator for those items which are passed all over the system?

No, the dependency would still be there, but instead of being explicit, it's now implicit.

As long as you have too many constructors arguments, at least you know that you have a problem. If you introduce a Service Locator, you still have all your original problems, but now you've also violated encapsulation. You've only made the underlying problems harder to detect, without addressing any of them.

Service Locator is a bona fide anti-pattern; it solves nothing.

Community
  • 1
  • 1
Mark Seemann
  • 209,566
  • 41
  • 390
  • 671
  • But should a logger be an explicit dependency? I think it's something that anyway would be all over the system so why not hide it and understand that it's everywhere. There are adaptors for Process, DateTime, Task and other classes that are there simply for testing purposes, are they true dependencies or just noise? – Ziv Nov 29 '15 at 12:03
  • 1
    [Logging shouldn't be an explicit dependency.](http://stackoverflow.com/a/7906547/126014) Time I would [inject as necessary, but alternatively you can also use an Ambient Context](http://stackoverflow.com/a/2425739/126014), which is *not* a Service Locator. – Mark Seemann Nov 29 '15 at 12:47