3 ms·
If it's possible in your particular language/framework, I would instead use setter-injection, and reserve constructor parameters for things the object truly nee
by Terr_ 12y ago
If it's possible in your particular language/framework, I would instead use setter-injection, and reserve constructor parameters for things the object truly needs access to before it can exist. In other words, let your design be guided by some of the basic principles you'd follow if you didn't have a dependency-injection system at all.
Assuming constructor-injection is your only choice (or the only choice you can use autowiring for)... then this technique depends on making the correct guess about how people will use the object. In this case, you're predicting that most of the time a cache will not be wanted.
If it were the other way around, I would instead make it a required parameter, and provide a convenient dummy/no-op Cache implementation people could use.
- sprain 12y agoActually, in my example, a cache will _always_ be used. It is mandatory to use a cache and therefore, if none is provided, a default cache is used. That's why it put it into the constructor.
- deleted 12y ago[deleted]
- Terr_ 12y agoIs SomeCache a dummy or no-op item, or does it contain an actual implementation, e.g. file or database access? To what extent is it important to make sure the person wiring things up knows and approves of what SomeCache does?
- sprain 12y agoSomeCache is a real, functioning implementation. Maybe cache is a bad example. It could also be a HTTP client to fetch some data over an api. Let's say the library by default uses Guzzle. But if a user for some reason wants to inject his own implementation of Guzzle or even BuzzBrowser (which is compatible for basic operations) instead, he can. For most simple projects, especially without a framework, the default implementation does the job and would save you some code.