5 ms·
It's an anti-pattern. It's a workaround for a serious language defect. I've written my own DI back in the days (way before Guice existed) but... Using DI is
by martinced 14y ago
It's an anti-pattern. It's a workaround for a serious language defect.
I've written my own DI back in the days (way before Guice existed) but...
Using DI is just a glorified way to have "globals".
One better solution in TFA's example is to pass a high-order function whose "functionality" is to provide the time.
Wanna unit test? Pass in a modified function giving back the time you want.
That's just one way to do it.
DI is a fugly beast disguised as "good practice" but it really ain't. It complicates the code and is basically a hack allowing to more or less be able to test non-functional code. Really sad.
--
"Patterns means 'I've run out of language"
- Peaker 14y agoBut passing in a function providing the time is a form of "dependency injection". It is a shitty name for the practice, but that's at least one way I saw the term "dependency injection" used.
- raverbashing 14y agoWell said DI is not good. It's a workaround for lack of flexibility disguised as a 'good practice'
- lusr 14y ago> Using DI is just a glorified way to have "globals". How so? > Wanna unit test? Pass in a modified function giving back the time you want. Right. And all DI does is make it possible for the following constructor to be invoked without special knowledge or adverse coupling: interface IArticleService { void Publish(); } class ArticleService : IArticleService { protected IArticleRepository ArticleRepository; protected ITimeService TimeService; public ArticleService(IArticleRepository articleRepository, ITimeService timeService) { ArticleRepository = articleRepository; TimeService = timeService; } public void Publish(int id) { ArticleRepository.Publish(id, TimeService.Now); } }
- hackinthebochs 14y ago>One better solution in TFA's example is to pass a high-order function whose "functionality" is to provide the time. Having a function or an interface as an argument is functionally equivalent. In fact, the interface is more expressive than the function as it describes more behavior than a simple function does. In both cases there is an "inversion of control" where the caller has to specify what object is passed in. So claiming that one is better than the other seems more personal preference than fact.