Ree
Ree

Reputation: 6211

Injection of seldom used services - constructor vs method

This question is about testable software design based on mostly value objects and services.

Here's an example of an API of a simple service that can save data to files.

saveToFile(data, fileName)
saveToUniqueFile(data, fileNameGenerator)

fileNameGenerator is a service that generates random file names. It is used to find a unique file name to save data to. In this example fileNameGenerator is injected as a method parameter.

One of the alternatives is constructor injection which would simplify the API:

saveToFile(data, fileName)
saveToUniqueFile(data)

Saving to a unique file certainly won't be used every time, so it would seem that a mandatory constructor parameter should not be required. On the other hand, services usually communicate via data and here we have a service and it does clutter the API a bit.

Are there any potential problems/inconveniences of passing services around as method parameters? Should constructor injection still be preferred in such situations?

Upvotes: 2

Views: 95

Answers (2)

Mark Seemann
Mark Seemann

Reputation: 233197

Passing services around as parameters is quite problematic, because you never know when you need them. Methods and their parameters constitute your API, whereas the constructor doesn't. Using the constructor to inject services gives you a much larger degree of freedom because it allows you to decouple dependencies from the API expressed by the methods.

Otherwise you'd have to pass the method argument around to all methods in your API on the off chance that one or two of them might need it.

Even when a service is only used once in a while, it's rarely an issue to use inject them via constructors.

Upvotes: 5

lettucemode
lettucemode

Reputation: 445

It depends on whether it makes more sense in the context of your program what the saveToUniqueFile() method "belongs" to. If you are working with objects that logically should be able to save themselves, then use constructor injection. If the saving of objects is managed by another, larger object or service then use the method parameter thing.

If you go with the service as a method parameter, make sure you're passing it by reference.

Upvotes: 0

Related Questions