155

I'm refactoring a class and adding a new dependency to it. The class is currently taking its existing dependencies in the constructor. So for consistency, I add the parameter to the constructor.
Of course, there are a few subclasses plus even more for unit tests, so now I am playing the game of going around altering all the constructors to match, and it's taking ages.
It makes me think that using properties with setters is a better way of getting dependencies. I don't think injected dependencies should be part of the interface to constructing an instance of a class. You add a dependency and now all your users (subclasses and anyone instantiating you directly) suddenly know about it. That feels like a break of encapsulation.

This doesn't seem to be the pattern with the existing code here, so I am looking to find out what the general consensus is, pros and cons of constructors versus properties. Is using property setters better?

apaderno
  • 28,547
  • 16
  • 75
  • 90
Niall Connaughton
  • 15,518
  • 10
  • 52
  • 48

15 Answers15

131

Well, it depends :-).

If the class cannot do its job without the dependency, then add it to the constructor. The class needs the new dependency, so you want your change to break things. Also, creating a class that is not fully initialized ("two-step construction") is an anti-pattern (IMHO).

If the class can work without the dependency, a setter is fine.

cuongle
  • 74,024
  • 28
  • 151
  • 206
sleske
  • 81,358
  • 34
  • 189
  • 227
  • 11
    I think it's many cases it is preferable to use the Null Object pattern and stick with requiring the references on the constructor. This avoids all null checking and the increased cyclomatic complexity. – Mark Lindell Mar 29 '10 at 20:05
  • 3
    @Mark: Good point. However, the question was about adding a dependency to an existing class. Then keeping a no-arg constructor allows for backward compatibility. – sleske Mar 30 '10 at 00:46
  • What about when the dependency is needed to function, but a default injection of that dependency will usually suffice. Then should that dependency be "overridable" by property or a constructor overload? – Patrick Szalapski Aug 26 '10 at 15:15
  • 1
    @Patrick: By "the class cannot do its job w/o the dependency", I meant that there is no reasonable default (e.g. the class requires a DB connection). In your situation, both would work. I'd still usually opt for the constructor approach, because it reduces complexity (what if e.g. the setter is called twice)? – sleske Aug 27 '10 at 00:02
  • Caveat: The Visual Studio forms designer seems to cry and die if you use constructor injection on user controls. – Maslow Feb 09 '11 at 16:45
  • @Maslow: Yes, quite a few frameworks aren't really designed for dependency injection; I guess it wasn't common when they were designed. For example Java Beans and classes meant to be persisted using Hibernate require setters for all fields :-(. – sleske Feb 09 '11 at 17:00
  • 1
    A good writeup on this here http://explorejava.com/different-types-of-bean-injection-in-spring/ – Eldhose Abraham Dec 27 '17 at 12:24
21

The users of a class are supposed to know about the dependencies of a given class. If I had a class that, for example, connected to a database, and didn't provide a means to inject a persistence layer dependency, a user would never know that a connection to the database would have to be available. However, if I alter the constructor I let the users know that there is a dependency on the persistence layer.

Also, to prevent yourself from having to alter every use of the old constructor, simply apply constructor chaining as a temporary bridge between the old and new constructor.

public class ClassExample
{
    public ClassExample(IDependencyOne dependencyOne, IDependencyTwo dependencyTwo)
        : this (dependnecyOne, dependencyTwo, new DependnecyThreeConcreteImpl())
    { }

    public ClassExample(IDependencyOne dependencyOne, IDependencyTwo dependencyTwo, IDependencyThree dependencyThree)
    {
        // Set the properties here.
    }
}

One of the points of dependency injection is to reveal what dependencies the class has. If the class has too many dependencies, then it may be time for some refactoring to take place: Does every method of the class use all the dependencies? If not, then that's a good starting point to see where the class could be split up.

Doctor Blue
  • 3,769
  • 6
  • 40
  • 63
  • Of course constructor chaining only works if there is a reasonable default value for the new parameter. But otherwise you cannot avoid breaking things anyway... – sleske Oct 01 '09 at 12:24
  • Usually, you would use whatever you were using in the method prior to dependency injection as the default parameter. Ideally, this would make the new constructor addition a clean refactoring, as the behavior of the class would not change. – Doctor Blue Oct 01 '09 at 12:37
  • 1
    I take your point about resource managing dependencies like database connections. I think the problem in my case is that the class I'm adding a dependency to has several subclasses. In an IOC container world where the property would be set by the container, using the setter would at least relieve the pressure on constructor interface duplication between all the subclasses. – Niall Connaughton Oct 01 '09 at 12:43
18

Of course, putting on the constructor means that you can validate all at once. If you assign things into read-only fields then you have some guarantees about your object's dependencies right from construction time.

It is a real pain adding new dependencies, but at least this way the compiler keeps complaining until it's correct. Which is a good thing, I think.

Joe
  • 46,419
  • 33
  • 155
  • 245
11

If you have large number of optional dependencies (which is already a smell) then probably setter injection is the way to go. Constructor injection better reveals your dependencies though.

epitka
  • 17,275
  • 20
  • 88
  • 141
10

The general preferred approach is to use constructor injection as much as possible.

Constructor injection exactly states what are the required dependencies for the object to function properly - nothing is more annoying than newing up an object and having it crashing when calling a method on it because some dependency is not set. The object returned by a constructor should be in a working state.

Try to have only one constructor, it keeps the design simple and avoids ambiguity (if not for humans, for the DI container).

You can use property injection when you have what Mark Seemann calls a local default in his book "Dependency Injection in .NET": the dependency is optional because you can provide a fine working implementation but want to allow the caller to specify a different one if needed.

(Former answer below)


I think that constructor injection are better if the injection is mandatory. If this adds too many constructors, consider using factories instead of constructors.

The setter injection is nice if the injection is optional, or if you want to change it halfway trough. I generally don't like setters, but it's a matter of taste.

Philippe
  • 3,945
  • 3
  • 38
  • 56
  • I'd argue that usually changing injection halfway through is bad style (because you are adding hidden state to your object). But no rule w/o exception of course... – sleske Oct 01 '09 at 12:25
  • Yep, that why I said I didn't like setter too much... I like the constructor approach as then it cannot be changed. – Philippe Oct 01 '09 at 12:34
  • "If this adds too many constructors, consider using factories instead of constructors." You basically defer any run time exceptions and might even get things wrongs and end up getting stuck with a service locator implementation. – MeTitus Sep 09 '16 at 14:39
  • @Marco that is my former answer and you are right. If there are many constructors, I would argue that the class does too many things :-) Or consider an abstract factory. – Philippe Sep 12 '16 at 07:16
8

It's largely a matter of personal taste. Personally I tend to prefer the setter injection, because I believe it gives you more flexibility in the way that you can substitute implementations at runtime. Furthermore, constructors with a lot of arguments are not clean in my opinion, and the arguments provided in a constructor should be limited to non-optional arguments.

As long as the classes interface (API) is clear in what it needs to perform its task, you're good.

nkr1pt
  • 4,691
  • 5
  • 35
  • 55
  • please specify why you are downvoting? – nkr1pt Oct 01 '09 at 12:18
  • 3
    Yes, constructors with a lot of arguments are bad. That's why you refactor classes with lots of constructor parameters :-). – sleske Oct 01 '09 at 12:19
  • 10
    @nkr1pt: Most people (me included) agree that setter injection is bad if it allows you to create a class that fail at runtime if the injection is not done. I believe someone therefore objected to your statement of it being personal taste. – sleske Oct 01 '09 at 12:21
7

I prefer constructor injection because it helps "enforce" a class's dependency requirements. If it's in the c'tor, a consumer has to set the objects to get the app to compile. If you use setter injection they may not know they have a problem until run time - and depending on the object, it might be late in run time.

I still use setter injection from time to time when the injected object maybe needs a bunch of work itself, like initialization.

ctacke
  • 66,480
  • 18
  • 94
  • 155
7

I personally prefer the Extract and Override "pattern" over injecting dependencies in the constructor, largely for the reason outlined in your question. You can set the properties as virtual and then override the implementation in a derived testable class.

Russ Cam
  • 124,184
  • 33
  • 204
  • 266
6

I perfer constructor injection, because this seems most logical. Its like saying my class requires these dependencies to do its job. If its an optional dependency then properties seem reasonable.

I also use property injection for setting things that the container does not have a references to such as an ASP.NET View on a presenter created using the container.

I dont think it breaks encapsulation. The inner workings should remain internal and the dependencies deal with a different concern.

David Kiff
  • 1,200
  • 2
  • 11
  • 24
  • Thanks for your answer. It certainly seems the constructor is the popular answer. However I do think it breaks encapsulation in some way. Pre-dependency injection, the class would declare and instantiate any concrete types it needed to do its job. With DI, subclasses (and any manual instantiators) now know what tools a base class is using. You add a new dependency and now you have to chain the instance through from all the subclasses, even if they don't need to use the dependency themselves. – Niall Connaughton Oct 01 '09 at 12:36
  • Just wrote a nice long answer and lost it due to an exception on this site!! :( In summary, the baseclass is usually used to re-use logic. This logic could quite easily go into the subclass... so you could think of the baseclass and subclass = one concern, that is dependent on multiple external objects, that do different jobs. The fact you have dependencies, does not mean you need to expose anything you would have previously kept private. – David Kiff Oct 01 '09 at 14:42
3

One option that might be worth considering is composing complex multiple-dependencies out of simple single dependencies. That is, define extra classes for compound dependencies. This makes things a little easier WRT constructor injection - fewer parameters per call - while still maintaining the must-supply-all-dependencies-to-instantiate thing.

Of course it makes most sense if there's some kind of logical grouping of dependencies, so the compound is more than an arbitrary aggregate, and it makes most sense if there are multiple dependents for a single compound dependency - but the parameter block "pattern" has been around for a long time, and most of those that I've seen have been pretty arbitrary.

Personally, though, I'm more a fan of using methods/property-setters to specify dependencies, options etc. The call names help describe what is going on. It's a good idea to provide example this-is-how-to-set-it-up snippets, though, and make sure the dependent class does enough error checks. You might want to use a finite state model for the setup.

3

I recently ran into a situation where I had multiple dependencies in a class, but only one of the dependencies was necessarily going to change in each implementation. Since the data access and error logging dependencies would likely only be changed for testing purposes, I added optional parameters for those dependencies and provided default implementations of those dependencies in my constructor code. In this way, the class maintains its default behavior unless overridden by the consumer of the class.

Using optional parameters can only be accomplished in frameworks that support them, such as .NET 4 (for both C# and VB.NET, though VB.NET has always had them). Of course, you can accomplish similar functionality by simply using a property that can be reassigned by the consumer of your class, but you don't get the advantage of immutability provided by having a private interface object assigned to a parameter of the constructor.

All of this being said, if you are introducing a new dependency that must be provided by every consumer, you're going to have to refactor your constructor and all code that consumers your class. My suggestions above really only apply if you have the luxury of being able to provide a default implementation for all of your current code but still provide the ability to override the default implementation if necessary.

Community
  • 1
  • 1
Ben McCormack
  • 32,086
  • 48
  • 148
  • 223
1

Constructor injection does explicitly reveal the dependencies, making code more readable and less prone to unhandled run-time errors if arguments are checked in the constructor, but it really does come down to personal opinion, and the more you use DI the more you'll tend to sway back and forth one way or the other depending on the project. I personally have issues with code smells like constructors with a long list of arguments, and I feel that the consumer of an object should know the dependencies in order to use the object anyway, so this makes a case for using property injection. I don't like the implicit nature of property injection, but I find it more elegant, resulting in cleaner-looking code. But on the other hand, constructor injection does offer a higher degree of encapsulation, and in my experience I try to avoid default constructors, as they can have an ill effect on the integrity of the encapsulated data if one is not careful.

Choose injection by constructor or by property wisely based on your specific scenario. And don't feel that you have to use DI just because it seems necessary and it will prevent bad design and code smells. Sometimes it's not worth the effort to use a pattern if the effort and complexity outweighs the benefit. Keep it simple.

David Spenard
  • 789
  • 7
  • 10
1

This is an old post, but if it is needed in future maybe this is of any use:

https://github.com/omegamit6zeichen/prinject

I had a similar idea and came up with this framework. It is probably far from complete, but it is an idea of a framework focusing on property injection

Markus
  • 195
  • 1
  • 11
0

It depends on how you want to implement. I prefer constructor injection wherever I feel the values that go in to the implementation doesnt change often. Eg: If the compnay stragtegy is go with oracle server, I will configure my datsource values for a bean achiveing connections via constructor injection. Else, if my app is a product and chances it can connect to any db of the customer , I would implement such db configuration and multi brand implementation through setter injection. I have just taken an example but there are better ways of implementing the scenarios I mentioned above.

  • 1
    Even when coding in-house, I always code from the point of view that I am a independent contractor developing code intended to be redistributable. I assume it is going to be open source. This way, I way I make sure that the code is modular and pluggable and follows SOLID principles. – Fred Mar 24 '16 at 21:13
0

When to use Constructor injection?
When we want to make sure that the Object is created with all of its dependencies and to ensure that required dependencies are not null.

When to use Setter injection?
When we are working with optional dependencies that can be assigned reasonable default values within the class. Otherwise, not-null checks must be performed everywhere the code uses the dependency. Additionally, setter methods make objects of that class open to reconfiguration or re-injection at a later time.

Sources: Spring documentation , Java Revisited