<?xml version="1.0" encoding="UTF-8"?><!-- generator="wordpress/2.0.11" -->
<rss version="2.0" 
	xmlns:content="http://purl.org/rss/1.0/modules/content/">
<channel>
	<title>Comments on: Setter injection versus constructor injection and the use of @Required</title>
	<link>http://blog.springsource.com/main/2007/07/11/setter-injection-versus-constructor-injection-and-the-use-of-required/</link>
	<description>The voice of SpringSource</description>
	<pubDate>Thu, 21 Aug 2008 01:27:25 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.0.11</generator>

	<item>
		<title>by: Bert van Brakel</title>
		<link>http://blog.springsource.com/main/2007/07/11/setter-injection-versus-constructor-injection-and-the-use-of-required/#comment-113000</link>
		<pubDate>Mon, 14 Jul 2008 07:21:21 +0000</pubDate>
		<guid>http://blog.springsource.com/main/2007/07/11/setter-injection-versus-constructor-injection-and-the-use-of-required/#comment-113000</guid>
					<description>Oh, and using the seperate FooOpts concreate class instead of the interface is easier for spring integration, as you just create another config entry for the FooOpts bean, and pass that in as a constructor arg to the Foo bean.</description>
		<content:encoded><![CDATA[<p>Oh, and using the seperate FooOpts concreate class instead of the interface is easier for spring integration, as you just create another config entry for the FooOpts bean, and pass that in as a constructor arg to the Foo bean.
</p>
]]></content:encoded>
				</item>
	<item>
		<title>by: Bert van Brakel</title>
		<link>http://blog.springsource.com/main/2007/07/11/setter-injection-versus-constructor-injection-and-the-use-of-required/#comment-112999</link>
		<pubDate>Mon, 14 Jul 2008 07:14:09 +0000</pubDate>
		<guid>http://blog.springsource.com/main/2007/07/11/setter-injection-versus-constructor-injection-and-the-use-of-required/#comment-112999</guid>
					<description>My preference for beans with a long list of constructors args is to use a configuration bean. As in

public class Foo{
    private final Service service;
    private final SomethingElse somethingElse;

    public Foo(FooOptions opts){
        assert( null != opts  );
  
        service = opts.service;
        somethingElse = opts.somethingElse;
        //don't perform checks on opts, instead on local vars, as callers may have changed opts in the meantime
        assert( null != service );
        assert( null != somethingElse );
    }
}

public class FooOptions{
    public Service service;
    public SomethingElse somethingElse;
    get/set....
}

You could also use the getters/setters in the options bean.

IMHO the advantage of this approach is that if subclasses need further args, just subclass the options bean, and no further changes to your classes are required.

It would be nice if Java supported automatic generation of constructor options beans (ie like named arguments I guess), or allowed inner classes without the need for an instance of the outer class so that these options can be kept in the same file.

Another approach is using an interface:

public class Foo {
	public Foo(FooOpts opts) {
                //..assert(...)
		service = opts.getService();
                somethingElse = opts.getSomethingElse();
                //..assert(...)
	}

	public interface FooOpts {
		public SomethingElse getSomethingeElse();
		public Service getService();
	}
}

and an example usage might be:

Foo foo = new Foo(new Foo.FooOpts(){
	public Service getService() {				
		return "My Service";
	}
	public SomethingElse getSomethingElse() {				
		return "SomethingElse";
	}
});


My personal take on setters vs constructors, is that the setters clutter up the API you are trying to expose, and you also end up with a lot of boring boilerplate get/set. IMHO objects should expose business logic, and not all the other junk for settings the object up. In the case of an options object, it doesn't contain any business logic, its just a transfer object, in which case get/set is fine and doesn't add to the confusion</description>
		<content:encoded><![CDATA[<p>My preference for beans with a long list of constructors args is to use a configuration bean. As in</p>
<p>public class Foo{<br />
    private final Service service;<br />
    private final SomethingElse somethingElse;</p>
<p>    public Foo(FooOptions opts){<br />
        assert( null != opts  );</p>
<p>        service = opts.service;<br />
        somethingElse = opts.somethingElse;<br />
        //don&#039;t perform checks on opts, instead on local vars, as callers may have changed opts in the meantime<br />
        assert( null != service );<br />
        assert( null != somethingElse );<br />
    }<br />
}</p>
<p>public class FooOptions{<br />
    public Service service;<br />
    public SomethingElse somethingElse;<br />
    get/set&#8230;.<br />
}</p>
<p>You could also use the getters/setters in the options bean.</p>
<p>IMHO the advantage of this approach is that if subclasses need further args, just subclass the options bean, and no further changes to your classes are required.</p>
<p>It would be nice if Java supported automatic generation of constructor options beans (ie like named arguments I guess), or allowed inner classes without the need for an instance of the outer class so that these options can be kept in the same file.</p>
<p>Another approach is using an interface:</p>
<p>public class Foo {<br />
	public Foo(FooOpts opts) {<br />
                //..assert(&#8230;)<br />
		service = opts.getService();<br />
                somethingElse = opts.getSomethingElse();<br />
                //..assert(&#8230;)<br />
	}</p>
<p>	public interface FooOpts {<br />
		public SomethingElse getSomethingeElse();<br />
		public Service getService();<br />
	}<br />
}</p>
<p>and an example usage might be:</p>
<p>Foo foo = new Foo(new Foo.FooOpts(){<br />
	public Service getService() {<br />
		return &#034;My Service&#034;;<br />
	}<br />
	public SomethingElse getSomethingElse() {<br />
		return &#034;SomethingElse&#034;;<br />
	}<br />
});</p>
<p>My personal take on setters vs constructors, is that the setters clutter up the API you are trying to expose, and you also end up with a lot of boring boilerplate get/set. IMHO objects should expose business logic, and not all the other junk for settings the object up. In the case of an options object, it doesn&#039;t contain any business logic, its just a transfer object, in which case get/set is fine and doesn&#039;t add to the confusion
</p>
]]></content:encoded>
				</item>
	<item>
		<title>by: Peter Lawrey</title>
		<link>http://blog.springsource.com/main/2007/07/11/setter-injection-versus-constructor-injection-and-the-use-of-required/#comment-49855</link>
		<pubDate>Wed, 19 Sep 2007 21:24:42 +0000</pubDate>
		<guid>http://blog.springsource.com/main/2007/07/11/setter-injection-versus-constructor-injection-and-the-use-of-required/#comment-49855</guid>
					<description>My preference is to use constructors for manditory arguments and IntelliJ's @NotNull annotation to check arguments which cannot be null. I also use setters for optional arguments. (With @NotNull as approriate)

Does anyone know how to configure Spring to use the Common Annotations 1.0 which come with Java 6. e.g. @PostConstruct, @PreDestroy, @Resource and @ConstructorProperties ?</description>
		<content:encoded><![CDATA[<p>My preference is to use constructors for manditory arguments and IntelliJ&#039;s @NotNull annotation to check arguments which cannot be null. I also use setters for optional arguments. (With @NotNull as approriate)</p>
<p>Does anyone know how to configure Spring to use the Common Annotations 1.0 which come with Java 6. e.g. @PostConstruct, @PreDestroy, @Resource and @ConstructorProperties ?
</p>
]]></content:encoded>
				</item>
	<item>
		<title>by: Alef Arendsen</title>
		<link>http://blog.springsource.com/main/2007/07/11/setter-injection-versus-constructor-injection-and-the-use-of-required/#comment-48357</link>
		<pubDate>Fri, 14 Sep 2007 09:37:11 +0000</pubDate>
		<guid>http://blog.springsource.com/main/2007/07/11/setter-injection-versus-constructor-injection-and-the-use-of-required/#comment-48357</guid>
					<description>Hey Chris,

thanks for your comments. I'll try to update the blog post when I have time, because mentioning the possibility to mix constructor injection and setter injection is definitely something that should have been done from the start.</description>
		<content:encoded><![CDATA[<p>Hey Chris,</p>
<p>thanks for your comments. I&#039;ll try to update the blog post when I have time, because mentioning the possibility to mix constructor injection and setter injection is definitely something that should have been done from the start.
</p>
]]></content:encoded>
				</item>
	<item>
		<title>by: Chris Beams</title>
		<link>http://blog.springsource.com/main/2007/07/11/setter-injection-versus-constructor-injection-and-the-use-of-required/#comment-48323</link>
		<pubDate>Fri, 14 Sep 2007 07:08:54 +0000</pubDate>
		<guid>http://blog.springsource.com/main/2007/07/11/setter-injection-versus-constructor-injection-and-the-use-of-required/#comment-48323</guid>
					<description>Looks like my XML example from the comment above got treated as HTML.  Here it is again (very simple, just demonstrating combining constructor and setter injection within a single bean declaration):

&#60;bean id="blogCommenter" class="org.example.BlogCommenter"&#62;
    &#60;constructor-arg value="Chris"/&#62; &#60;!-- first name, required --&#62;
    &#60;constructor-arg value="Beams"/&#62; &#60;!-- last name, required --&#62;
    &#60;property value="S"/&#62; &#60;!-- middle initial, optional --&#62;
&#60;/bean&#62;</description>
		<content:encoded><![CDATA[<p>Looks like my XML example from the comment above got treated as HTML.  Here it is again (very simple, just demonstrating combining constructor and setter injection within a single bean declaration):</p>
<p>&lt;bean id=&#034;blogCommenter&#034; class=&#034;org.example.BlogCommenter&#034;&gt;<br />
    &lt;constructor-arg value=&#034;Chris&#034;/&gt; &lt;!&#8211; first name, required &#8211;&gt;<br />
    &lt;constructor-arg value=&#034;Beams&#034;/&gt; &lt;!&#8211; last name, required &#8211;&gt;<br />
    &lt;property value=&#034;S&#034;/&gt; &lt;!&#8211; middle initial, optional &#8211;&gt;<br />
&lt;/bean&gt;
</p>
]]></content:encoded>
				</item>
	<item>
		<title>by: Chris Beams</title>
		<link>http://blog.springsource.com/main/2007/07/11/setter-injection-versus-constructor-injection-and-the-use-of-required/#comment-48322</link>
		<pubDate>Fri, 14 Sep 2007 07:02:46 +0000</pubDate>
		<guid>http://blog.springsource.com/main/2007/07/11/setter-injection-versus-constructor-injection-and-the-use-of-required/#comment-48322</guid>
					<description>Alef,

Thanks for the thoughtful treatment of these two alternatives.  Constructor vs. setter injection is something that often becomes a matter of religion.  It's not nearly so black-and-white, and I think that (amongst your other points) drawing a distinction between the needs of application code vs. framework code is spot on.  While I strongly prefer constructor injection whenever appropriate, there are certainly contexts where setter injection is preferable (optional parameters are the obvious case here).  It's worth pointing out that these two approaches are not mutually exclusive either.  I often mix and match constructor and setter injection, e.g.:


     &lt;!-- first name, required --&gt;
     &lt;!-- last name, required --&gt;
     &lt;!-- middle initial, optional --&gt;


This is an overly simple example (one would likely never declare such a bean), but it expresses the idea.

As you mention, it translates to Java code that properly leverages constructors to ensure an object is always in a valid state:

BlogCommenter commenter = new BlogCommenter("Chris", "Beams");
commenter.setMiddleInitial('S');

This reduces the likelihood of NullPoninterExceptions down the road, and specifies a clear contract to users of your class as to how it should be used.  No guesswork as to which setters 'must' be called, etc.  These benefits, IMHO, outweigh the decreased readability caused by the fact that constructor args do not have names in the spring configuration XML, particularly because classes may be used in contexts outside Spring configuration.  In these cases, we want to rely on the language as much as possible to inform us about how to use the class.  Constructors are the natural choice here.

Now, if only the p: namespace allowed for some syntactic sugar around constructor args ;-)

- Chris</description>
		<content:encoded><![CDATA[<p>Alef,</p>
<p>Thanks for the thoughtful treatment of these two alternatives.  Constructor vs. setter injection is something that often becomes a matter of religion.  It&#039;s not nearly so black-and-white, and I think that (amongst your other points) drawing a distinction between the needs of application code vs. framework code is spot on.  While I strongly prefer constructor injection whenever appropriate, there are certainly contexts where setter injection is preferable (optional parameters are the obvious case here).  It&#039;s worth pointing out that these two approaches are not mutually exclusive either.  I often mix and match constructor and setter injection, e.g.:</p>
<p>     <!-- first name, required --><br />
     <!-- last name, required --><br />
     <!-- middle initial, optional --></p>
<p>This is an overly simple example (one would likely never declare such a bean), but it expresses the idea.</p>
<p>As you mention, it translates to Java code that properly leverages constructors to ensure an object is always in a valid state:</p>
<p>BlogCommenter commenter = new BlogCommenter(&#034;Chris&#034;, &#034;Beams&#034;);<br />
commenter.setMiddleInitial(&#039;S');</p>
<p>This reduces the likelihood of NullPoninterExceptions down the road, and specifies a clear contract to users of your class as to how it should be used.  No guesswork as to which setters &#039;must&#039; be called, etc.  These benefits, IMHO, outweigh the decreased readability caused by the fact that constructor args do not have names in the spring configuration XML, particularly because classes may be used in contexts outside Spring configuration.  In these cases, we want to rely on the language as much as possible to inform us about how to use the class.  Constructors are the natural choice here.</p>
<p>Now, if only the p: namespace allowed for some syntactic sugar around constructor args <img src='http://blog.springsource.com/main/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> </p>
<p>- Chris
</p>
]]></content:encoded>
				</item>
	<item>
		<title>by: Revue de Presse Xebia par J2EE, AgilitÃ© et SOA&#160;:&#160;Le blog de Xebia France</title>
		<link>http://blog.springsource.com/main/2007/07/11/setter-injection-versus-constructor-injection-and-the-use-of-required/#comment-34669</link>
		<pubDate>Mon, 16 Jul 2007 15:24:22 +0000</pubDate>
		<guid>http://blog.springsource.com/main/2007/07/11/setter-injection-versus-constructor-injection-and-the-use-of-required/#comment-34669</guid>
					<description>[...] Setter injection versus constructor injection and the use of @Required [...]</description>
		<content:encoded><![CDATA[<p>[&#8230;] Setter injection versus constructor injection and the use of @Required [&#8230;]
</p>
]]></content:encoded>
				</item>
	<item>
		<title>by: peter</title>
		<link>http://blog.springsource.com/main/2007/07/11/setter-injection-versus-constructor-injection-and-the-use-of-required/#comment-34200</link>
		<pubDate>Sat, 14 Jul 2007 08:29:44 +0000</pubDate>
		<guid>http://blog.springsource.com/main/2007/07/11/setter-injection-versus-constructor-injection-and-the-use-of-required/#comment-34200</guid>
					<description>å¼ºçƒˆæŠ—è®®ä¸?æ”¯æŒ?ä¸­æ–‡ï¼Œè€?å¤–æ€Žä¹ˆæ²¡æœ‰ä¸€ç‚¹å›½é™…åŒ–ç²¾ç¥žå‘¢ï¼Ÿ

This website should surport Chinese!Thank you!</description>
		<content:encoded><![CDATA[<p>å¼ºçƒˆæŠ—è®®ä¸?æ”¯æŒ?ä¸­æ–‡ï¼Œè€?å¤–æ€Žä¹ˆæ²¡æœ‰ä¸€ç‚¹å›½é™…åŒ–ç²¾ç¥žå‘¢ï¼Ÿ</p>
<p>This website should surport Chinese!Thank you!
</p>
]]></content:encoded>
				</item>
	<item>
		<title>by: Brendan Lawlor</title>
		<link>http://blog.springsource.com/main/2007/07/11/setter-injection-versus-constructor-injection-and-the-use-of-required/#comment-33994</link>
		<pubDate>Fri, 13 Jul 2007 15:11:40 +0000</pubDate>
		<guid>http://blog.springsource.com/main/2007/07/11/setter-injection-versus-constructor-injection-and-the-use-of-required/#comment-33994</guid>
					<description>That should have read 'C plus-plus' but somehow the '  ' disappeared.</description>
		<content:encoded><![CDATA[<p>That should have read &#039;C plus-plus&#039; but somehow the &#039;  &#039; disappeared.
</p>
]]></content:encoded>
				</item>
	<item>
		<title>by: Brendan Lawlor</title>
		<link>http://blog.springsource.com/main/2007/07/11/setter-injection-versus-constructor-injection-and-the-use-of-required/#comment-33970</link>
		<pubDate>Fri, 13 Jul 2007 13:08:50 +0000</pubDate>
		<guid>http://blog.springsource.com/main/2007/07/11/setter-injection-versus-constructor-injection-and-the-use-of-required/#comment-33970</guid>
					<description>Alef,
   From a simple OO design point of view, what you recommend about the use of constructor injection makes perfect sense. I allowed myself to be swayed into using setter construction by the message that i21 was putting out back when we started using Spring, but what I learned back in my C   days is that classes should prevent, as much as possible, the construction of instances with invalid state. In these days of increasingly anemic models, the least a class can do to earn it's wage is to act as gatekeeper over its own state. 
In the end it's much better to use the simplest, least Spring-dependent way of defining which data members (including dependencies) are required and which are not. Thanks for bringing up this matter again.</description>
		<content:encoded><![CDATA[<p>Alef,<br />
   From a simple OO design point of view, what you recommend about the use of constructor injection makes perfect sense. I allowed myself to be swayed into using setter construction by the message that i21 was putting out back when we started using Spring, but what I learned back in my C   days is that classes should prevent, as much as possible, the construction of instances with invalid state. In these days of increasingly anemic models, the least a class can do to earn it&#039;s wage is to act as gatekeeper over its own state.<br />
In the end it&#039;s much better to use the simplest, least Spring-dependent way of defining which data members (including dependencies) are required and which are not. Thanks for bringing up this matter again.
</p>
]]></content:encoded>
				</item>
</channel>
</rss>
