Hacker News new | ask | show | jobs
by jasonlotito 5534 days ago
Question regarding the injection. I've found that while injecting dependencies is good, I still prefer the brevity of not having to declare the common case. Basically, I allow an injection to take place, but make it optional, and if one isn't passed, I use the common case, which in effect makes a call to a getInstance.

Any thoughts on that?

2 comments

Well, that is a workable solution, but then, I'm sure you're already aware of that, seeing as you use it already ;) Personally I prefer having the object appear in the published interface, it helps highlight the existence of a dependency, but your way doesn't seem horrible either. I suspect that it depends a lot the language you're using. I'm a C programmer, and optional parameters are quite verbose in C, so I would never choose your solution, but in Ruby or Javascript your solution could be quite clean.
My big concern is always implementing a solution and not seeing an otherwise obvious problem. Hence the question. =)

As a PHP guy, setting up optional params are easy, so I like the solution.

I have done that as well. That is one of the strategies we have used on my team @ work. One specific case was where we were basically being integrated into a much larger, older component and they had their own way of doing things. Dependency injection wasn't an option. So we did a default for that case and exposed the dependencies so that we could mock them out in our tests.