<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Rich Newman</title>
	<atom:link href="http://richnewman.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://richnewman.wordpress.com</link>
	<description></description>
	<lastBuildDate>Sun, 29 Jan 2012 00:19:01 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='richnewman.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Rich Newman</title>
		<link>http://richnewman.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://richnewman.wordpress.com/osd.xml" title="Rich Newman" />
	<atom:link rel='hub' href='http://richnewman.wordpress.com/?pushpress=hub'/>
		<item>
		<title>Blurry Text with Small Fonts in WPF</title>
		<link>http://richnewman.wordpress.com/2011/12/20/blurry-text-with-small-fonts-in-wpf/</link>
		<comments>http://richnewman.wordpress.com/2011/12/20/blurry-text-with-small-fonts-in-wpf/#comments</comments>
		<pubDate>Tue, 20 Dec 2011 01:58:07 +0000</pubDate>
		<dc:creator>richnewman</dc:creator>
				<category><![CDATA[.net]]></category>
		<category><![CDATA[fonts]]></category>
		<category><![CDATA[wpf]]></category>
		<category><![CDATA[blurry]]></category>

		<guid isPermaLink="false">http://richnewman.wordpress.com/?p=694</guid>
		<description><![CDATA[Introduction The difficulties with text rendering in WPF have been well documented elsewhere.  However, every time I get a blurry button I can&#8217;t remember how to fix it.  This brief post shows the usual solutions. TextOptions.TextFormattingMode With small font sizes the default WPF text rendering can lead to text looking very blurry.  This is particularly [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=richnewman.wordpress.com&amp;blog=909413&amp;post=694&amp;subd=richnewman&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<h4>Introduction</h4>
<p>The difficulties with text rendering in WPF have been <a href="http://stackoverflow.com/questions/190344/wpf-blurry-fonts-problem-solutions">well documented elsewhere</a>.  However, every time I get a blurry button I can&#8217;t remember how to fix it.  This brief post shows the usual solutions.</p>
<h4>TextOptions.TextFormattingMode</h4>
<p>With small font sizes the default WPF text rendering can lead to text looking very blurry.  This is particularly a problem on controls (e.g. text on buttons), where we often use small fonts.</p>
<p>In .Net 4 Microsoft finally gave us a solution to this problem, which is to set TextOptions.TextFormattingMode = “Display” (instead of “Ideal”).  This snaps everything to the pixel grid.  However, this mode doesn&#8217;t look good at large text sizes, so there’s no easy solution to this problem.</p>
<h4>Other TextOptions</h4>
<p>Other TextOptions are</p>
<p>1.  TextHintingMode (Animated/Auto/Fixed)</p>
<p>This just tells the renderer to use smoother but less clear rendering for animated text.  It won’t fix the blurry text problem for static text (which should have Auto or Fixed set).</p>
<p>2.  TextRenderingMode (Aliased/Auto/ClearType/GrayScale).</p>
<p>Tells the renderer how to draw.  This DOES affect blurriness.  In particular using Aliased rather than the default Auto can be good at small sizes.</p>
<h4>Effect of These Options</h4>
<p>Below, with font size 12, the first line is the default (Ideal/Auto).  This is quite blurry.  The second line is Display/Auto (less blurry) and the third line is Display/Aliased (not at all blurry, but a bit jagged).  The second two lines are the options usually used to fix the problem.</p>
<p><a href="http://techmeanderings.files.wordpress.com/2011/12/textrendering.png" target="_parent"><img title="TextRendering" src="http://techmeanderings.files.wordpress.com/2011/12/textrendering.png?w=630" alt="" /></a></p>
<p>This is the same but at font size 24, which highlights the problem since now Ideal/Auto (the first line) probably is ideal:</p>
<p><a href="http://techmeanderings.files.wordpress.com/2011/12/textrendering22.png" target="_parent"><img title="TextRendering2" src="http://techmeanderings.files.wordpress.com/2011/12/textrendering22.png?w=630" alt="" /></a></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/richnewman.wordpress.com/694/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/richnewman.wordpress.com/694/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/richnewman.wordpress.com/694/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/richnewman.wordpress.com/694/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/richnewman.wordpress.com/694/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/richnewman.wordpress.com/694/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/richnewman.wordpress.com/694/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/richnewman.wordpress.com/694/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/richnewman.wordpress.com/694/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/richnewman.wordpress.com/694/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/richnewman.wordpress.com/694/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/richnewman.wordpress.com/694/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/richnewman.wordpress.com/694/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/richnewman.wordpress.com/694/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=richnewman.wordpress.com&amp;blog=909413&amp;post=694&amp;subd=richnewman&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://richnewman.wordpress.com/2011/12/20/blurry-text-with-small-fonts-in-wpf/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/20ffeb59bba855d0069ee936add87d8b?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Rich</media:title>
		</media:content>

		<media:content url="http://techmeanderings.files.wordpress.com/2011/12/textrendering.png?w=630" medium="image">
			<media:title type="html">TextRendering</media:title>
		</media:content>

		<media:content url="http://techmeanderings.files.wordpress.com/2011/12/textrendering22.png?w=630" medium="image">
			<media:title type="html">TextRendering2</media:title>
		</media:content>
	</item>
		<item>
		<title>Review of a Composite Application Block Project</title>
		<link>http://richnewman.wordpress.com/2011/09/13/review-of-a-composite-application-block-project/</link>
		<comments>http://richnewman.wordpress.com/2011/09/13/review-of-a-composite-application-block-project/#comments</comments>
		<pubDate>Tue, 13 Sep 2011 03:59:23 +0000</pubDate>
		<dc:creator>richnewman</dc:creator>
				<category><![CDATA[.net]]></category>
		<category><![CDATA[CAB]]></category>
		<category><![CDATA[Composite Application Block]]></category>
		<category><![CDATA[dotnet]]></category>
		<category><![CDATA[Prism]]></category>
		<category><![CDATA[Spring.Net]]></category>

		<guid isPermaLink="false">http://richnewman.wordpress.com/?p=637</guid>
		<description><![CDATA[Introduction In late 2007 I wrote a series of articles on Microsoft’s Composite Application Block (CAB).  At that time I was running a team that was developing a user interface framework that used the CAB. We’re now four years on and that framework is widely used throughout our department.  There are currently modules from eleven [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=richnewman.wordpress.com&amp;blog=909413&amp;post=637&amp;subd=richnewman&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<h1>Introduction</h1>
<p>In late 2007 I wrote a <a href="http://richnewman.wordpress.com/intro-to-cab-toc/">series of articles on Microsoft’s Composite Application Block</a> (CAB).  At that time I was running a team that was developing a user interface framework that used the CAB.</p>
<p>We’re now four years on and that framework is widely used throughout our department.  There are currently modules from eleven different development teams in production.  There are modules that do trade booking, trade management, risk management, including real-time risk management, curve marking, other market data management, and so on.  All of those were written by different teams, yet it appears to the user that this is one application.</p>
<p>So the framework is a success.  However, it’s only a qualified success.</p>
<p>This article will look back at the goals, design decisions, and implementation history of the project, and why it’s only a qualified success.  It will look at what we did right, what we did wrong, and some of the limitations of the CAB itself (which apply equally to its successor, Prism).</p>
<p>Hopefully this will be of interest.  It isn’t the kind of thing I usually write about and will of course be a personal view:  I’m not going to pretend I’m totally unbiased.</p>
<h1>Design Goals</h1>
<h2>Original Overall Goals</h2>
<p>The project had two very simple goals originally:</p>
<ol>
<li>A single client application that a user (in this case, a trader) would use for everything they need to do.</li>
<li>Multiple development teams able to easily contribute to this application, working independently of each other.</li>
</ol>
<p>I suspect these are the aims of most CAB or Prism projects.</p>
<h2>Do You Actually Need a Single Client Application?</h2>
<p>An obvious question arising from these goals is why you would need an application of this kind.</p>
<p>Historically there have tended to be two approaches to building big and complex trading applications:</p>
<ol>
<li>The IT department will create one huge monolithic application.  One large development team will build it all.</li>
<li>The IT department breaks the problem up and assigns smaller development teams to develop separate applications to do each part.  This is a much more common approach than 1/.</li>
</ol>
<p>Both of these approaches work, and both mean you don’t need a client application of the kind we are discussing.  However, neither of these approaches works very well:</p>
<ul>
<li>Monolithic applications quickly become difficult to maintain and difficult to release without major regression testing.</li>
<li>Equally users don&#8217;t like having to log into many different applications.  This is particularly true if those applications are built by the same department but all behave in different ways.  It can also be difficult to make separate applications communicate with each other, or share data, in a sensible way.</li>
</ul>
<p>So there definitely is a case for trying to create something that fulfils our original design goals above and avoids these problems.   Having said that it’s clearly more important to actually deliver the underlying functionality.  If it’s in several separate applications that matters less than failing to deliver it altogether.</p>
<h2>More Detailed Goals</h2>
<p>For our project we also had some more detailed goals:</p>
<ul>
<li>Ease of use for the developer.  I have personally been compelled to use some very unpleasant user interface frameworks and was keen that this should not be another one of those.</li>
<li>A standardized look and feel.  The user should feel this was one application, not several applications glued together in one window.</li>
<li>Standard re-usable components, in particular a standard grid and standard user controls.  The user controls should include such things as typeahead counterparty lookups, book lookups, and security lookups based on the organization&#8217;s standard repositories for this data.  That is, they should include business functionality.</li>
<li>Simple security (authentication and authorization) based on corporate standards.</li>
<li>Simple configuration, including saving user settings and layouts.</li>
<li>Simple deployment.  This should include individual development teams being able to deploy independently of other teams.</li>
</ul>
<p>As I&#8217;ll discuss, it was some of the things that we left off that list came to back to haunt us later on.</p>
<h2>Goals re Serverside Communication</h2>
<p>A further goal was use of our strategic architecture serverside, in particular for trade management.  For example, we wanted components that would construct and send messages to our servers in a standard way.  I won&#8217;t discuss the success or failure of this goal in detail here as it’s a long and chequered story, and not strictly relevant to the CAB and the user interface framework.</p>
<h1>Technical Design</h1>
<h2>Technical Design: Technologies</h2>
<p>The technologies we used to build this application were:</p>
<ul>
<li>Microsoft C# and Windows Forms</li>
<li>Microsoft&#8217;s Patterns and Practices Group&#8217;s Composite Application Block (the CAB)</li>
<li>DevExpress&#8217; component suite</li>
<li>Tibco EMS and Gemstone&#8217;s Gemfire for serverside communication and caching</li>
</ul>
<p>As I&#8217;ve already discussed, this document is going to focus purely on the clientside development.</p>
<p>In 2007 these were logical choices for a project of this kind.  I&#8217;ll discuss some of the more detailed design decisions in the sections below.</p>
<h1>Things We Did (Fairly) Well</h1>
<p>As I said this is a personal view: I&#8217;m not sure all our developers would agree that all of this was done well.</p>
<h2>Ease of Use</h2>
<p>Designing for ease of use is, of course, quite difficult.  We have done a number of things to make the project easy to use, some of which I&#8217;ll expand on below.  These include:</p>
<ul>
<li>Developers write vanilla user controls.  There&#8217;s no need to implement special interfaces, inherit from base classes or use any complex design pattern.</li>
<li>Almost all core functionality is accessed through simple services that the developer just gets hold of and calls.  So for example to show your user control you get an instance of the menu service and call a show method.  We used singleton service locators so the services could be accessed without resorting to CAB dependency injection.</li>
<li>Good documentation freely available on a wiki</li>
<li>A standard onboarding process for new teams, including setting up a template module.  This module has a &#8217;hello world&#8217; screen that shows the use of the menus and other basic functionality.</li>
</ul>
<h2>Developers Not Forced to Learn the Composite Application Block (CAB)</h2>
<p>As mentioned above, one of the key goals of the project was simplicity of use.  The CAB is far from simple to use: I wrote a <a href="http://richnewman.wordpress.com/intro-to-cab-toc/">25 part introductory blog article</a> on it and still hadn&#8217;t covered it all.</p>
<p>As a result we took the decision early on that developers would not be compelled to use the CAB actually within their modules.  We were keen that developers would <strong>not</strong> have to learn the intricacies of the CAB, and in particular would not have to use the CAB&#8217;s rather clunky dependency injection in their code.</p>
<p>However, obviously we were using the CAB in our core framework.  This made it difficult to isolate our developers from the CAB completely:</p>
<ul>
<li>As mentioned above we exposed functionality to the developers through CAB services.  However we gave them a simple service locator so they didn&#8217;t have to know anything about the CAB to use these services.</li>
<li>We also used some CAB events that developers would need to sink.  However since this involves decorating a public method with an attribute we didn&#8217;t think this was too difficult.</li>
</ul>
<p>As already mentioned, to facilitate this we wrote a &#8216;template&#8217; module, and documentation on how to use it.  This was a very simple dummy module that showed how to do all the basics.  In particular it showed what code to write at startup (a couple of standard methods), how to get hold of a service, and how to set up a menu item and associated event.</p>
<h2>Versioning</h2>
<p>We realized after a few iterations of the system that we needed a reasonably sophisticated approach to versioning and loading of components.  As a result we wrote an assembly loader.  This:</p>
<ul>
<li>Allows each module to keep its own assemblies in its own folder</li>
<li>Allows different modules to use different versions of the same assembly</li>
<li>Also allows different modules to explicitly share the same version of an assembly</li>
</ul>
<p>Our default behaviour is that when loading an assembly that&#8217;s not in the root folder, the system checks all module folders for an assembly of that name and loads the latest version found.  This means teams can release interface assemblies without worrying about old versions in other folders.</p>
<h2>Versioning of Core Components</h2>
<p>For core components clearly there&#8217;s some code that has to be used by everyone (e.g. the shell form itself, and menus).  This <strong>has</strong> to be backwards compatible at each release because we don&#8217;t want everyone to have to release simultaneously.  We achieve this through the standard CAB pattern of interface assemblies: module teams only access core code through interfaces that can be extended, but not changed.</p>
<p>However, as mentioned above, the core team also writes control assemblies that aren&#8217;t backwards compatible: teams include them in their own module, and can upgrade whenever they want without affecting anyone else.</p>
<h2>User Interface Design</h2>
<p>For the user interface design, after a couple of iterations we settled on simple docking in the style of Visual Studio.  For this we used <a href="http://sourceforge.net/projects/dockpanelsuite/">Weifen Luo&#8217;s excellent docking manager</a>, and wrote a wrapper for it that turned it into a CAB workspace.  For menuing we used the ribbon bars in the DevExpress suite.</p>
<p>The use of docking again keeps things simple for our developers.  We have a menu service with a method to be called that just displays a vanilla user control in a docked (or floating) window.</p>
<h2>Deployment</h2>
<p>In large organizations it&#8217;s not uncommon for the standard client deployment mechanisms to involve complex processes and technology.  Our organization has this problem.  Early on in this project it was mandated that we would use the standard deployment mechanisms.</p>
<p>We tried hard to wrap our corporate process in a way that made deployment as simple as possible.  To some extent we have succeeded, although we are (inevitably) very far from a simple process.</p>
<h2>Configuration</h2>
<p>For configuration (eventually) we used another team&#8217;s code that wrapped our centralized configuration system to allow our developers to store configuration data.  This gives us hierarchies of data in a centralized database.  It means you can easily change a setting for all users, groups of users, or an individual user, and can do this without the need for a code release.</p>
<h2>Module Interaction</h2>
<p>Clientside component interaction is achieved by using the standard CAB mechanisms.  If one team wants to call another team&#8217;s code they simply have to get hold of a service in the same way as they do for the core code, and make a method call on an interface.  This works well, and is one advantage of using the CAB.  Of course the service interface has to be versioned and backwards compatible, but this isn&#8217;t difficult.</p>
<h2>Security</h2>
<p>For security we again wrapped our organization&#8217;s standard authentication and authorization systems so they could easily be used in our CAB application.  We extended the standard .Net Principal and Identity objects to allow authorization information to be directly accessed, and also allowed this information to be accessed via a security service.</p>
<p>One thing that we didn&#8217;t do so well here was the control of authorization permissions.  These have proliferated, and different teams have handled different aspects of this in different ways.  This was in spite of us setting up what we thought was a simple standard way of dealing with the issue.  The result of this is that it&#8217;s hard to understand the permissioning just by looking at our permissioning system.</p>
<h1>Things We Didn&#8217;t Do So Well</h1>
<p>As mentioned above, the things that didn&#8217;t go so well were largely the things we didn&#8217;t focus on in our original list of goals.</p>
<p>Most of these issues are about resource usage on the client.  This list is far from comprehensive: we do have other problems with what we&#8217;ve done, of course, but the issues highlighted here are the ones causing the most problems at the time of writing.</p>
<p>The problems included:</p>
<h2>Threading</h2>
<h3>The Problem</h3>
<p>We decided early on to allow each team to do threading in the way they thought was appropriate, and didn&#8217;t provide much guidance on threading.  This was a mistake, for a couple of reasons.</p>
<h4>Threading and Exception Handling</h4>
<p>The first problem we had with threading was the simple one of background threads throwing exceptions with no exception handler in place.  As I&#8217;m sure you know, this is pretty much guaranteed to crash the entire application messily (which in this case means bringing down 11 teams&#8217; code).  Of course it&#8217;s easy to fix if you follow some simple guidelines whenever you spawn a background thread.  We have an exception hander that can be hooked up with one line of code and that can deal with appropriate logging and thread marshalling.  We put how to do this, and dire warnings about the consequences of not doing so, in our documentation, but to no avail.  In the end we had highly-paid core developers going through other teams&#8217; code looking for anywhere they spawned a thread and then complaining to their managers if they hadn&#8217;t put handlers in.</p>
<h4>Complex Threading Models</h4>
<p>Several of our teams were used to writing serverside code with complex threading models.  They replicated these clientside, even though most of our traders don&#8217;t have anything better than a dual core machine, so any complex threading model in a workstation client is likely to be counterproductive.</p>
<p>Some of these models tend to throw occasional threading exceptions that are unreproducible and close to undebuggable.</p>
<h3>What We Should Have Done</h3>
<p>In retrospect we should have :</p>
<ul>
<li>Provided some clear guidance for the use of threading in the client.</li>
<li>Written some simple threading wrappers and insisted the teams use them, horrible though that is.</li>
<li>Insisted that ANY use of threading be checked by the core team (i.e. a developer that knew about user interface threading).  The wrappers would have made it easy for us to check where threads were being spawned incorrectly (and without handlers).</li>
</ul>
<h2>Start Up</h2>
<h3>The Basic Problem</h3>
<p>We have a problem with the startup of the system as well: it&#8217;s very slow.</p>
<p>Our standard startup code (in our template module) is very close to the standard SCSF code.  This allows teams to set up services and menu items when the entire application starts and the module is loaded.</p>
<p>This means the module teams have a hook that lets them run code at startup.  The intention here is that you instantiate a class or two, and it should take almost no time.  We didn&#8217;t think that teams would start using it to load their data, or start heartbeats, or worse, to fire off a bunch of background threads to load their data.  However, we have all of this in the system.</p>
<p>Of course the reason for this is that the place where this code should actually be is when a user clicks a menu item to load the team&#8217;s screen for the first time.  For heartbeats, it&#8217;s a little hard to control startup and closedown when a screen opens and closes: it&#8217;s much easier to just start your heartbeats when the application starts.  For data loading for a screen, if this is slow it becomes very obvious if it happens when a user requests a screen.</p>
<p>However, the impact of this happening over 11 development teams&#8217; code is that the system is incredibly slow to start, and very very fragile at startup.  It will often spend a couple of minutes showing the splash screen and then keel over with an incomprehensible error message (or none).  As a result most traders keep the system open all the time (including overnight).  But an obvious consequence is that they are very reluctant to restart, even if they have a problem that we know a restart will fix.  Also all machines are rebooted at the weekend in our organization, so they have to sit through the application startup on a Monday morning in any case.</p>
<p>One further problem is that no individual team has any incentive to improve their startup speed: it&#8217;s just a big pool of slowness and you can&#8217;t tell if module X is much slower than module Y as a user.  If any one team moves to proper service creation at startup it won&#8217;t have a huge overall effect.  We have 11 teams and probably no one team contributes more than a couple of minutes to the overall startup.  It&#8217;s the cumulative effect that&#8217;s the problem.</p>
<h3>What We Should Have Done</h3>
<p>This is one area where we should just have policed what was going on better, and been very firm about what is and is not allowed to be run at startup.  At one stage I proposed fixing the problem by banning ANY module team&#8217;s code from running at startup, and I think if I were to build an application of this kind again then that&#8217;s what I&#8217;d do.  However, clearly a module has to be able to set up its menu items at startup (or the user won&#8217;t be able to run anything).  So we&#8217;d have to develop a way of doing this via config for this to work, which would be ugly.</p>
<p>One other thing that would really help would be the ability to restart an individual module without restarting the entire system.</p>
<h2>Memory Usage</h2>
<h3>The Problem</h3>
<p>We effectively have 11 applications running in the same process.  So with memory usage we have similar problems to the startup problems: every team uses as much memory as they think they need, but when you add it all up we can end up with instances of the system using well over 1GB of memory.  On a heavily-loaded trader&#8217;s machine this is a disaster: we&#8217;ve even had to get another machine for some traders just to run our application.</p>
<p>To be honest, this would be a problem for any complex trading environment.  If we had 11 separate applications doing the same things as ours the problem would probably be worse.</p>
<p>However, as above there&#8217;s no incentive for any individual team to address the problem: it&#8217;s just a big pool that everyone uses and no-one can see that module X is using 600MB.</p>
<h3>What We Should Have Done</h3>
<p>Again here better policing would have helped: we should have carefully checked every module&#8217;s memory requirements and told teams caching large amounts of data not to.  However, in the end this is a problem that is very hard to avoid: I don&#8217;t think many teams are caching huge amounts of data, it&#8217;s just there&#8217;s a lot of functionality in the client.</p>
<p>One thing that will help here is the move to 64-bit, which is finally happening in our organization.  All our traders have a ceiling of 4GB of memory at present (of which, as you know, over 1GB is used by Windows), so a 1GB application is a real problem.</p>
<h2>Use of Other Dependency Injection Frameworks (Spring.Net)</h2>
<h3>The Problem</h3>
<p>One unexpected effect of the decision not to compel teams to use the CAB was that a number of teams decided to use Spring.Net for dependency injection within their modules, rather than using the CAB dependency injection.  I have some sympathy with this decision, and we didn&#8217;t stop them.  However, Spring.Net isn&#8217;t well-designed for use in a framework of this kind and it did cause a number of problems.</p>
<ul>
<li>The biggest of these is that Spring uses a number of process-wide singletons.  We had difficulties getting them to play nicely with our assembly loading.  This has resulted in everyone currently having to use the same (old) version of Spring.Net, and upgrading being a major exercise.</li>
<li>Handling application context across several modules written by different teams proved challenging.</li>
<li>If you use XML configuration in Spring.Net (which everyone does) then types in other assemblies are usually referenced using the simple assembly name only.  This invalidated some of our more ambitious assembly loading strategies.</li>
<li>The incomprehensibility associated with Spring.Net&#8217;s exception messages on initial configuration is made worse when you have multiple modules at startup.</li>
</ul>
<p>We also had some similar problems re singletons and versioning with the clientside components of our caching technology.  Some code isn&#8217;t really compatible with single-process composite applications.</p>
<h3>What We Should Have Done</h3>
<p>Again we should have policed this better: many of the problems described above are solvable, or could at least have been mitigated by laying down some guidelines early on.</p>
<h1>What I&#8217;d Change If I Did This Again</h1>
<p>The &#8216;what we should have done&#8217; sections above indicate some of the things I&#8217;d change if I am ever responsible for building another framework of this kind.  However, there are two more fundamental (and very different) areas that I would change:</p>
<h2>Code Reviews</h2>
<p>In the &#8216;what we should have done&#8217; sections above I&#8217;ve frequently mentioned that we should have monitored what was happening in the application more carefully.  The reasons we didn&#8217;t were partially due to resourcing, but also to some extent philosophical.  Most of our development teams are of high quality, so we didn&#8217;t feel we needed to be carefully monitoring them and telling them what to do.</p>
<p>As you can see from the problems we&#8217;ve had, this was a mistake.  We should have identified the issues above early, and then reviewed all code going into production to ensure that there weren&#8217;t threading, startup, memory or any other issues.</p>
<h2>Multiple Processes</h2>
<p>The second thing I&#8217;d change is technical.  I now think it&#8217;s essential in a project of this kind to have some way of running clientside code in separate processes.  As we&#8217;ve seen many of the problems we&#8217;ve had have arisen because everything is running in the same process:</p>
<ul>
<li>Exceptions can bring the process down, or poorly-written code can hang it</li>
<li>It&#8217;s hard to identify how much each module is contributing to memory usage or startup time</li>
<li>There&#8217;s no way of shutting down and unloading a misbehaving module</li>
</ul>
<p>I think I&#8217;d ideally design a framework that had multiple message loops and gave each team its own process in which they could display their own user interface.  This is tricky, but not impossible to do well.</p>
<p>Note that I&#8217;d still write the application as a framework.  I&#8217;d make sure the separate processes could communicate with each other easily, and that data could be cached and shared between the processes.</p>
<p>As an aside a couple of alternatives to this are being explored in our organization at present (although I am not personally involved).  The first is to simply break up the application into multiple simpler applications.  The problem with this is that it doesn&#8217;t really solve the memory usage or startup time problems, and in fact arguably makes them worse.  The second is to write a framework that has multiple processes but keeps the user interface for all development teams in the same process.  This is obviously easier to do technically than my suggestion above.  However for many of our modules it would require quite a bit of refactoring: we need to split our the user interface code cleanly and run it in a separate process to the rest of the module code.</p>
<p style="text-align:left;">
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/richnewman.wordpress.com/637/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/richnewman.wordpress.com/637/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/richnewman.wordpress.com/637/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/richnewman.wordpress.com/637/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/richnewman.wordpress.com/637/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/richnewman.wordpress.com/637/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/richnewman.wordpress.com/637/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/richnewman.wordpress.com/637/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/richnewman.wordpress.com/637/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/richnewman.wordpress.com/637/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/richnewman.wordpress.com/637/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/richnewman.wordpress.com/637/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/richnewman.wordpress.com/637/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/richnewman.wordpress.com/637/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=richnewman.wordpress.com&amp;blog=909413&amp;post=637&amp;subd=richnewman&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://richnewman.wordpress.com/2011/09/13/review-of-a-composite-application-block-project/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/20ffeb59bba855d0069ee936add87d8b?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Rich</media:title>
		</media:content>
	</item>
		<item>
		<title>A Beginner&#8217;s Guide To Credit Default Swaps (Part 4)</title>
		<link>http://richnewman.wordpress.com/2011/08/08/a-beginners-guide-to-credit-default-swaps-part-4/</link>
		<comments>http://richnewman.wordpress.com/2011/08/08/a-beginners-guide-to-credit-default-swaps-part-4/#comments</comments>
		<pubDate>Mon, 08 Aug 2011 01:34:52 +0000</pubDate>
		<dc:creator>richnewman</dc:creator>
				<category><![CDATA[beginners guide]]></category>
		<category><![CDATA[cds]]></category>
		<category><![CDATA[clearing house]]></category>
		<category><![CDATA[credit default swap]]></category>
		<category><![CDATA[derivatives]]></category>
		<category><![CDATA[introduction]]></category>
		<category><![CDATA[swap execution facility]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[made easy]]></category>
		<category><![CDATA[SEF]]></category>

		<guid isPermaLink="false">http://richnewman.wordpress.com/?p=595</guid>
		<description><![CDATA[Introduction This post continues the discussion of changes in the credit default swap (CDS) since 2007.  Part 2 and part 3 of this series of articles discussed changes in the mechanics of CDS trading.  This part will discuss changes around how credit events are handled, and future changes in the market. Changes in the CDS Market [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=richnewman.wordpress.com&amp;blog=909413&amp;post=595&amp;subd=richnewman&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><strong>Introduction</strong></p>
<p>This post continues the discussion of changes in the credit default swap (CDS) since 2007.  <a href="http://richnewman.wordpress.com/2011/07/19/a-beginner%e2%80%99s-guide-to-credit-default-swaps-part-2/">Part 2</a> and <a href="http://richnewman.wordpress.com/2011/08/04/a-beginner%e2%80%99s-guide-to-credit-default-swaps-part-3/">part 3</a> of this series of articles discussed changes in the mechanics of CDS trading.  This part will discuss changes around how credit events are handled, and future changes in the market.</p>
<p><strong>Changes in the CDS Market re Credit Events Since 1997</strong></p>
<ul>
<li>Determination committees (DCs) have been set up to work out if a credit event has occurred, and to oversee various aspects of dealing with a credit event for the market.  A ‘determination committee’ is simply a group of CDS traders of various kinds, although overseen by ISDA (the standards body). The parties to one of the new standard contracts agree to be bound by the committee’s decisions.</li>
<li><a href="http://www.markit.com/cds/documentation/resource/credit_event_auction_primer.pdf">Auctions are now conducted</a> to determine the price to cash-settle credit default swaps when there is a credit event.  For this we need to determine the current price of the bonds in default.  To do this we get a group of dealers to quote prices at which they are prepared to trade the bonds (and may have to), and then calculate the price via an averaging process.  This can get quite complicated.  The determination committees oversee these auctions.</li>
<li>Classes of events that lead to credit events have been simplified.  In particular whether ‘restructuring’ is a credit event has been standardized (although the standards are different in North America, Asia and Europe).  ‘Restructuring’ means such things as changing the maturity of a bond, or changing its currency.</li>
<li>There is now a ‘lookback period’ for credit events regardless of when a CDS is traded.  What this means is that credit events that have happened in the past 60 days (only) can trigger a contract payout.  This simplifies things because the same CDS traded on different days is now treated identically in this regard.</li>
</ul>
<p><strong>Terminology and a Little History</strong></p>
<p>The changes described so far in this article were introduced in 2009.  For North America, which went first, this was known as <a href="http://www.markit.com/cds/announcements/resource/cds_big_bang.pdf">‘CDS Big Bang’</a>.  The standard contract terms thus introduced were known as the ‘Standard North American CDS Contract’ or ‘SNAC’ (pronounced ‘snack’).  The later changes in Europe were known as the <a href="http://www.markit.com/cds/announcements/resource/cds_small_bang_07202009_upd.pdf">‘CDS Small Bang’</a>.  <a href="http://www.markit.com/cds/announcements/resource/cds%20standardization%2020091210_update.pdf">The final standardization of Asian contracts</a> occurred later still.</p>
<p>Much more detail on all of this can be found on the links to the excellent MarkIt papers above.</p>
<p><strong>Future Changes</strong></p>
<p>Further standardization in the credit default swap market will occur as a result of the <a href="http://en.wikipedia.org/wiki/Obama_financial_regulatory_reform_plan_of_2009">Dodd-Frank Act in the USA</a>. This mandates that standard swaps (such as standard CDS) be traded through a &#8216;swap execution facility&#8217; (SEF). It further mandates that any such trades be cleared through a central clearing house.  Europe is likely to impose a similar regulatory regime, but is behind the United States.  More detail on SEFs and clearing houses is below.</p>
<p>The primary aims of these changes are:</p>
<p>1/ Greater transparency of trading. Currently many swaps are traded over-the-counter with no disclosure other than between the two counterparties. This makes it different to assess the size of the market, or the effects of a default.</p>
<p>2/ Reduced risk in the market overall from the bankruptcy of one participant.</p>
<p>The exact details of these changes are still being worked on by the regulators.</p>
<p><strong>Swap Execution Facilities (SEFs)</strong></p>
<p>At the time of writing <a href="http://streetwiseprofessor.com/?p=3964">it&#8217;s not even clear exactly what a &#8216;SEF&#8217; is</a>.  The Act defines a SEF as a “facility, trading system or platform in which multiple participants have the ability to execute or trade Swaps by accepting bids and offers made by other participants that are open to multiple participants”. That is, a SEF is a place where any participant can see and trade on current prices. There are some additional requirements of SEFs relating to providing public data relating to price and volume, and preventing market abuses.</p>
<p>In many ways a SEF will be very similar to an existing exchange. As mentioned the exact details are still being worked on.</p>
<p>A number of the existing electronic platforms for the trading of CDS are likely to become SEFs.</p>
<p><strong>Clearing Houses</strong></p>
<p><a href="http://en.wikipedia.org/wiki/Clearing_house_(finance)">Central clearing houses</a> are another mechanism for reducing risk in a market.</p>
<p>When a trade is done both parties to the trade can agree that it will be cleared through a clearing house.  This means that the clearing house becomes the counterparty to both sides of the trade: rather than bank A buying from bank B, bank A buys from the clearing house, and bank B sells to the clearing house.</p>
<p>Obviously the clearing house has no risk from the trades themselves.  The clearing house <strong>is</strong> exposed to the risk that either bank A or bank B goes bankrupt and thus can&#8217;t pay its obligations from the trade.  To mitigate this the clearing house will demand cash or other assets from both banks A and B.  This is known as &#8216;margin&#8217;.</p>
<p>The advantage of this arrangement is that the clearing house can guarantee that bank A will be unaffected even if bank B goes bankrupt.  The only counterparty risk for bank A is that the clearing house itself goes bankrupt.  This is unlikely since the clearing house will have no market risk, be well capitalized, and demands margin for all transactions.</p>
<p>Clearing houses and exchanges are often linked (and may be the same entity), but they are distinct concepts: the exchange is the place where you go to get prices and trade, the clearing house deals with the settlement of the trade. Usually clearing houses only have a restricted number of &#8216;members&#8217; who are allowed to clear trades. Anyone else wanting clearing services has to get them indirectly through one of these members.</p>
<p>At the time of writing there are already a few central clearing houses for credit default swaps in operation, and more are on the way.</p>
<p><strong>Conclusion</strong></p>
<p>Since 1997 contracts for credit default swaps have been standardized.  This has simplified the way in which the market works overall: it’s reduced the scope for difficulties when a credit event happens, simplified the processing of premium payments, and allowed similar CDS contracts to be netted together more easily.  At the same time it has made understanding the mechanics of the market more difficult.</p>
<p>Further changes are in the pipeline for the CDS market to use &#8216;swap execution facilities&#8217; and clearing houses.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/richnewman.wordpress.com/595/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/richnewman.wordpress.com/595/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/richnewman.wordpress.com/595/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/richnewman.wordpress.com/595/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/richnewman.wordpress.com/595/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/richnewman.wordpress.com/595/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/richnewman.wordpress.com/595/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/richnewman.wordpress.com/595/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/richnewman.wordpress.com/595/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/richnewman.wordpress.com/595/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/richnewman.wordpress.com/595/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/richnewman.wordpress.com/595/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/richnewman.wordpress.com/595/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/richnewman.wordpress.com/595/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=richnewman.wordpress.com&amp;blog=909413&amp;post=595&amp;subd=richnewman&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://richnewman.wordpress.com/2011/08/08/a-beginners-guide-to-credit-default-swaps-part-4/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/20ffeb59bba855d0069ee936add87d8b?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Rich</media:title>
		</media:content>
	</item>
		<item>
		<title>Closures in C#</title>
		<link>http://richnewman.wordpress.com/2011/08/06/closures-in-c/</link>
		<comments>http://richnewman.wordpress.com/2011/08/06/closures-in-c/#comments</comments>
		<pubDate>Sat, 06 Aug 2011 02:08:30 +0000</pubDate>
		<dc:creator>richnewman</dc:creator>
				<category><![CDATA[.net]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[closure]]></category>

		<guid isPermaLink="false">http://richnewman.wordpress.com/?p=601</guid>
		<description><![CDATA[Introduction There seems to be some confusion about closures in C#: people are mystified as to what they are and there’s even an implication that they don’t work the way you’d expect. As this short article will explain they are actually quite simple, and do work the way you’d expect if you’re an object oriented [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=richnewman.wordpress.com&amp;blog=909413&amp;post=601&amp;subd=richnewman&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><strong>Introduction</strong></p>
<p>There seems to be some confusion about closures in C#: people are mystified as to what they are and there’s even an implication that they don’t work the way you’d expect.</p>
<p>As this short article will explain they are actually quite simple, and do work the way you’d expect if you’re an object oriented programmer.  The article will also briefly look at why there is confusion surrounding them, and discuss whether they are an appropriate tool in an object oriented program.</p>
<p><strong>Closures</strong></p>
<p><a href="http://en.wikipedia.org/wiki/Closure_(computer_programming)">Wikipedia defines a closure</a> as ‘a first-class function with free variables that can be bound in the lexical environment’.  What that means is that a ‘closure’ is a function that can access variables from the environment where it is declared without them being explicitly passed in as parameters.  In object-oriented programming a method in a class is a closure of sorts: it can access fields of the class directly without needing them to be passed in.  However, more usually in C# ‘closure’ refers to a function declared as an anonymous delegate that uses variables that are not explicitly passed into it, but are available at the point it is created.</p>
<p><strong>Basic Example</strong></p>
<p>Consider the code below:</p>
<pre>        <span style="color:blue;font-family:Courier;">internal</span> <span style="color:blue;font-family:Courier;">void</span> <span style="color:olive;font-family:Courier;">MyFunction</span>()
         {
             <span style="color:blue;font-family:Courier;">int</span> <span style="color:olive;font-family:Courier;">x</span> = 1;
             Action <span style="color:olive;font-family:Courier;">action</span> = () =&gt; { <span style="color:olive;font-family:Courier;">x</span>++; <span style="color:#2b91af;font-family:Courier;">Console</span>.<span style="color:olive;font-family:Courier;">WriteLine</span>(<span style="color:olive;font-family:Courier;">x</span>); };
             <span style="color:olive;font-family:Courier;">action</span>();              <span style="color:green;font-family:Courier;">// Outputs '2'</span>
         }</pre>
<p>Here we define an anonymous delegate (a function) ‘action’, and call it.  This increments x and outputs it to the console, even though x isn’t passed into it.  x is simply declared in the ‘lexical environment’ (the calling method).</p>
<p>‘action’ is a closure, and we can say it is ‘closed over’ x, and that x is an ‘upvalue’.  Note that it’s only a closure because of the way it uses x.  Not all anonymous delegates are closures.</p>
<p>By the way, in the Java community anonymous functions frequently are referred to as ‘closures’.  (The Java community has been debating whether ‘closures’ should be added to the language for some time.)</p>
<p><strong>Where’s the Confusion?</strong></p>
<p>The example above is pretty clear and simple.  So how has it caused confusion?</p>
<p>The answer is that the value of x in MyFunction after the ‘action’ call is now 2.  Furthermore, x is completely shared between MyFunction and the action delegate: any code that changes the value in one changes the value in the other.</p>
<p>Consider the code below:</p>
<pre>        <span style="color:blue;font-family:Courier;">internal</span> <span style="color:blue;font-family:Courier;">void</span> <span style="color:olive;font-family:Courier;">MyFunction</span>()
         {
             <span style="color:blue;font-family:Courier;">int</span> <span style="color:olive;font-family:Courier;">x</span> = 1;
             Action <span style="color:olive;font-family:Courier;">action</span> = () =&gt; { <span style="color:olive;font-family:Courier;">x</span>++; <span style="color:#2b91af;font-family:Courier;">Console</span>.<span style="color:olive;font-family:Courier;">WriteLine</span>(<span style="color:olive;font-family:Courier;">x</span>); };
             <span style="color:olive;font-family:Courier;">action</span>();              <span style="color:green;font-family:Courier;">// Outputs '2'</span>
             <span style="color:olive;font-family:Courier;">x</span>++;
             <span style="color:olive;font-family:Courier;">action</span>();              <span style="color:green;font-family:Courier;">// Outputs '4'</span>
         }</pre>
<p>Here we call ‘action’, increment x in the calling method (MyFunction), and then call ‘action’ again.  Overall we started with x at 1, and incremented it 3 times, twice in our ‘action’ delegate and once in the calling method.  So it’s no surprise that the shared variable ends up with a value of 4.</p>
<p>This shows that we can change our ‘upvalue’ in the calling method and it is then reflected in our next call to the function: x is genuinely shared in this example.</p>
<p>Whilst this is a little odd (see below) it’s perfectly logical: x is shared between the calling method and any calls to our ‘action’ function.  There’s only one version of x.</p>
<p>This isn’t the way closures work in most functional programming languages (not that you could easily implement the example above, since all variables are immutable in functional languages).  The concept of closures has come from functional languages, so many people are surprised to find them working this way in C#.  There is more on this later.</p>
<p><strong>Closures and Scope</strong></p>
<p>This becomes even odder if we allow the local variable x to go out of scope (which would usually lead to it being destroyed), but retain a reference to the delegate that uses it:</p>
<pre>        <span style="color:blue;font-family:Courier;">internal</span> <span style="color:blue;font-family:Courier;">void</span> <span style="color:olive;font-family:Courier;">Run</span>()
        {
             Action <span style="color:olive;font-family:Courier;">action</span> = <span style="color:olive;font-family:Courier;">MyFunction</span>();
             <span style="color:olive;font-family:Courier;">action</span>();             <span style="color:green;font-family:Courier;">// Outputs '5'</span>
        }

        <span style="color:blue;font-family:Courier;">internal</span> Action <span style="color:olive;font-family:Courier;">MyFunction</span>()
        {
             <span style="color:blue;font-family:Courier;">int</span> <span style="color:olive;font-family:Courier;">x</span> = 1;
             Action <span style="color:olive;font-family:Courier;">action</span> = () =&gt; { <span style="color:olive;font-family:Courier;">x</span>++; <span style="color:#2b91af;font-family:Courier;">Console</span>.<span style="color:olive;font-family:Courier;">WriteLine</span>(<span style="color:olive;font-family:Courier;">x</span>); };
             <span style="color:olive;font-family:Courier;">action</span>();              <span style="color:green;font-family:Courier;">// Outputs '2'</span>
             <span style="color:olive;font-family:Courier;">x</span>++;
             <span style="color:olive;font-family:Courier;">action</span>();              <span style="color:green;font-family:Courier;">// Outputs '4'</span>
             <span style="color:blue;font-family:Courier;">return</span> <span style="color:olive;font-family:Courier;">action</span>;
        }</pre>
<p>Here our Run method retrieves the action delegate from MyFunction and calls it.  When it calls it the value of x is 4 (from the activity in MyFunction), so it increments that and outputs 5.  At this point MyFunction is out of scope so the local variable x would normally have been destroyed.</p>
<p>Again, logically this is what we’d expect, but it looks strange.</p>
<p>This also gives an indication that closures are hard to implement.</p>
<p><strong>A Little Odd?</strong></p>
<p>For an object-oriented programmer this is a little odd.  This is because we’re not used to being able to share local variables with a separate method in this way.</p>
<p>Normally if we want a method to act on a local variable we have to pass it in as a parameter.  If the local variable is a value type as above it gets copied, and changing it in the method will not affect its value in the calling method.  So if we wanted to use it in the calling method we’d have to pass it back explicitly as a return value or an output parameter.</p>
<p>Of course, there are good reasons why we don’t usually allow a method to access any variable in a calling method (quite apart from the practicalities of actually being able to do it with methods other than anonymous functions).  These are to do with encapsulation and ensuring we can maintain state in a way that’s easy to deal with.  We only really allow data to be shared at a class level, or globally if we’re using static variables, although in general we try to keep them to a minimum.</p>
<p>So in some ways closures of this kind break our usual object-oriented encapsulation.  My feeling is that they should be used sparingly in regular object-oriented code as a result.</p>
<p>Other writers have gone further than this, because if you don’t understand that an upvalue is fully shared between the anonymous function and the calling code you can get unexpected behaviour.  See, for example, this article <a href="http://marlongrech.wordpress.com/2010/06/02/closures-in-c-can-be-evil/">‘Closures in C# Can Be Evil’</a>.</p>
<p><strong>Conclusion</strong></p>
<p>The concepts behind closures in C# are actually fairly straightforward.  However, if we use them it’s important we understand them and the effects on scope, or we may get behaviour we don’t expect.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/richnewman.wordpress.com/601/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/richnewman.wordpress.com/601/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/richnewman.wordpress.com/601/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/richnewman.wordpress.com/601/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/richnewman.wordpress.com/601/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/richnewman.wordpress.com/601/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/richnewman.wordpress.com/601/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/richnewman.wordpress.com/601/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/richnewman.wordpress.com/601/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/richnewman.wordpress.com/601/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/richnewman.wordpress.com/601/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/richnewman.wordpress.com/601/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/richnewman.wordpress.com/601/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/richnewman.wordpress.com/601/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=richnewman.wordpress.com&amp;blog=909413&amp;post=601&amp;subd=richnewman&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://richnewman.wordpress.com/2011/08/06/closures-in-c/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/20ffeb59bba855d0069ee936add87d8b?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Rich</media:title>
		</media:content>
	</item>
		<item>
		<title>A Beginner’s Guide to Credit Default Swaps (Part 3)</title>
		<link>http://richnewman.wordpress.com/2011/08/04/a-beginner%e2%80%99s-guide-to-credit-default-swaps-part-3/</link>
		<comments>http://richnewman.wordpress.com/2011/08/04/a-beginner%e2%80%99s-guide-to-credit-default-swaps-part-3/#comments</comments>
		<pubDate>Thu, 04 Aug 2011 02:52:29 +0000</pubDate>
		<dc:creator>richnewman</dc:creator>
				<category><![CDATA[beginners guide]]></category>
		<category><![CDATA[cds]]></category>
		<category><![CDATA[credit default swap]]></category>
		<category><![CDATA[derivatives]]></category>
		<category><![CDATA[introduction]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://richnewman.wordpress.com/?p=590</guid>
		<description><![CDATA[Introduction Part 1 of this series of articles described the basic mechanics of a credit default swap. Part 2 started to describe some of the changes in the market since part 1 was written.  This part will continue that description by describing the upfront fee that is now paid on a standard CDS contract, and [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=richnewman.wordpress.com&amp;blog=909413&amp;post=590&amp;subd=richnewman&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><strong>Introduction</strong></p>
<p><a href="http://richnewman.wordpress.com/2007/12/09/a-beginners-guide-to-credit-default-swaps/">Part 1 of this series of articles</a> described the basic mechanics of a credit default swap.</p>
<p><a href="http://richnewman.wordpress.com/2011/07/19/a-beginner%e2%80%99s-guide-to-credit-default-swaps-part-2/">Part 2</a> started to describe some of the changes in the market since part 1 was written.  This part will continue that description by describing the upfront fee that is now paid on a standard CDS contract, and the impact of the changes on how CDS are quoted in the market.</p>
<p><strong>Standard Premiums mean there is a Fee</strong></p>
<p>Part 1 discussed how CDS contracts have been standardized.  One of the ways in which they have been standardized is that there are now standard premiums.</p>
<p>Now consider the case where I buy protection on a five-year CDS.  I enter into a standard contract with a premium of 500 basis points (5%).  It may be that the premium I would have paid under the old nonstandard contract for the same dates and terms would have been 450 basis points.  However, now I’m paying 500 basis points.</p>
<p>Clearly I need to be compensated for the 50 bps difference or I won’t want to enter into the trade under the new terms.</p>
<p>As a result an upfront fee is paid to me when the contract is started.  This represents the 50 basis points difference over the life of the trade, so that I am paying the same amount overall as under the old contract.</p>
<p>Note that in this case I (the protection buyer) am receiving the payment, but it could easily be that I pay this upfront fee (if, for example, the nonstandard contract would have traded at 550 bps).</p>
<p><strong>Upfront Fee Calculation</strong></p>
<p>The calculation of the fee from the ‘old’ premium (spread) is not trivial.  It takes into account discounting, and also the possibility that the reference entity will default, which would mean the premium would not be paid for the full life of the trade.  However, this calculation too has been standardized by the contracts body (ISDA).  There is a standard model that does it for us.</p>
<p><strong>The Full First Coupon means there is a Fee</strong></p>
<p>In the example in part 1 I discussed how I might pay for a full three months protection at the first premium payment date for a CDS trade, even though I hadn’t had protection for three months.</p>
<p>Once again I need compensation for this or I will prefer to enter into the old contract.  So once again there is a fee paid to me when I enter into the trade.</p>
<p>This is known as an ‘accrual payment’ because of the similarity to accrued interest payment for bonds.  Here the calculation is simple: it’s the premium rate applied to the face value of the trade for the period from the last premium payment date to the trade date.</p>
<p>That is, it’s the amount I’ll be paying for protection that I haven’t received as part of the first premium payment.  Note no discounting is applied to this.</p>
<p><strong>Upfront Fee/Accrual Payment</strong></p>
<p>So in summary the new contract standardization means that a payment is now always made when a standard CDS contract is traded.</p>
<p>Part of the payment is the upfront fee that compensates for the difference between the standard premium (100 or 500 bps in North America) and the actual premium for the trade.  This can be in either direction (payment from protection buyer to seller or vice versa).  Part of the payment is the accrual payment made to the protection buyer to compensate them for the fact that they have to make a full first coupon payment.</p>
<p><strong>How CDS are Quoted in the Market</strong></p>
<p>Prior to these changes CDS were traded by simply quoting the premium that would be paid throughout the life of the trade.<br />
With the contract standardization clearly the premium paid through the life of the trade will not vary with market conditions (it will always be 100 or 500 bps in North America, for example), so quoting it makes little sense.</p>
<p>Instead the dealers will quote one of:</p>
<p>a) Points Upfront<br />
‘Points upfront’ or just ‘points’ refer to the upfront fee as a percentage of the notional.  For example, a CDS might be quoted as 3 ‘points upfront’ to buy protection.  This means the upfront fee (excluding the accrual payment) is 3% of the notional.  ‘Points upfront’ have a sign: if the points are quoted as a negative then the protection buyer is paid the upfront fee by the protection seller.  If the points are positive it’s the other way around.</p>
<p>b)  Price<br />
With price we quote &#8216;like a bond&#8217;. We take price away from 100 to get points:<br />
That is, points = 100 – price.  So in the example above where a CDS is quoted as 3 points to buy protection, the price will be 97.   The protection buyer still pays the 3% as an upfront fee of course.</p>
<p>c)  Spread<br />
Dealers are so used to quoting spread that they have carried on doing so in some markets, even for standard contracts that pay a standard premium.  That is they still quote the periodic premium amount you would have been paying if you had bought prior to the standardization.  As already mentioned, there is a standard model for turning this number into the upfront fee that actually needs to be paid.</p>
<p><strong>Conclusion</strong></p>
<p>This part concludes the discussion of the changes in the mechanics of CDS trading since 2007.  As you can see, in many ways the standardization of the CDS market has actually made it more complicated.  The things to remember are that premiums, premium and maturity dates, and the amounts paid at premium dates have all been standardized in a standard contract.  This has meant there is an upfront fee for all standard CDS, and that they are quoted differently in the market from before.  It has also meant that CDS positions can be more easily netted against each other, and that the mechanics of calculating and settling premiums have been simplified.</p>
<p><a href="http://richnewman.wordpress.com/2011/08/08/a-beginners-guide-to-credit-default-swaps-part-4/">Part 4 of this series</a> will examine some of the other changes since 2007, and changes that are coming.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/richnewman.wordpress.com/590/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/richnewman.wordpress.com/590/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/richnewman.wordpress.com/590/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/richnewman.wordpress.com/590/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/richnewman.wordpress.com/590/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/richnewman.wordpress.com/590/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/richnewman.wordpress.com/590/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/richnewman.wordpress.com/590/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/richnewman.wordpress.com/590/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/richnewman.wordpress.com/590/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/richnewman.wordpress.com/590/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/richnewman.wordpress.com/590/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/richnewman.wordpress.com/590/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/richnewman.wordpress.com/590/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=richnewman.wordpress.com&amp;blog=909413&amp;post=590&amp;subd=richnewman&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://richnewman.wordpress.com/2011/08/04/a-beginner%e2%80%99s-guide-to-credit-default-swaps-part-3/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/20ffeb59bba855d0069ee936add87d8b?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Rich</media:title>
		</media:content>
	</item>
		<item>
		<title>A Beginner’s Guide to Credit Default Swaps (Part 2)</title>
		<link>http://richnewman.wordpress.com/2011/07/19/a-beginner%e2%80%99s-guide-to-credit-default-swaps-part-2/</link>
		<comments>http://richnewman.wordpress.com/2011/07/19/a-beginner%e2%80%99s-guide-to-credit-default-swaps-part-2/#comments</comments>
		<pubDate>Tue, 19 Jul 2011 03:46:05 +0000</pubDate>
		<dc:creator>richnewman</dc:creator>
				<category><![CDATA[beginners guide]]></category>
		<category><![CDATA[bonds]]></category>
		<category><![CDATA[cds]]></category>
		<category><![CDATA[credit default swap]]></category>
		<category><![CDATA[derivatives]]></category>
		<category><![CDATA[introduction]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://richnewman.wordpress.com/?p=583</guid>
		<description><![CDATA[Introduction Part 1 of the &#8216;Beginner&#8217;s Guide to Credit Default Swaps&#8217; was written in 2007. Since that time we have seen what many are calling the greatest financial crisis since the Great Depression, and a global recession. Rightly or wrongly, some of the blame for the crisis has been attributed to credit derivatives and speculation [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=richnewman.wordpress.com&amp;blog=909413&amp;post=583&amp;subd=richnewman&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><strong>Introduction</strong></p>
<p><a href="http://richnewman.wordpress.com/2007/12/09/a-beginners-guide-to-credit-default-swaps/">Part 1 of the &#8216;Beginner&#8217;s Guide to Credit Default Swaps&#8217;</a> was written in 2007. Since that time we have seen what many are calling the greatest financial crisis since the Great Depression, and a global recession.</p>
<p>Rightly or wrongly, some of the <a href="http://www.thestreet.com/story/10443559/credit-default-swaps-bad-enough-to-ban.html">blame for the crisis has been attributed to credit derivatives</a> and speculation in them.  This has led to calls for a more transparent and better regulated credit default swap (CDS) market. Furthermore the CDS market has grown very quickly, and by 2009 it had become clear that some simple changes to operational procedures would benefit everyone.</p>
<p>As a result many changes in the market have already been implemented, and more are on the way. This article will discuss these changes.  It will focus primarily on how the mechanics of trading a credit default swap have changed, rather than the history of how we got here or why these changes have been made. I&#8217;ll also briefly discuss the further changes that are on the way.</p>
<p><strong>Overview of the Changes</strong></p>
<p>The first thing to note is that nothing has fundamentally changed from the <a href="http://richnewman.wordpress.com/2007/12/09/a-beginners-guide-to-credit-default-swaps/">description of a credit default swap in part 1</a>. A credit default swap is still a contract that provides a kind of insurance against a company defaulting on its bonds. If you have read and understood part one then you should understand how a credit default swap works.</p>
<p>The main change that has happened is that credit default swap contracts have been standardized. This standardization falls into three broad categories:</p>
<ol>
<li>Changes to the premium, premium and maturity dates, and premium payments that simplify the mechanics of CDS trading.</li>
<li>Changes to the processes around identifying whether a credit event has occurred.</li>
<li>Changes to the processes around what happens when a credit event has occurred.</li>
</ol>
<p>Items 2 and 3 are extremely important, and have removed many of the problems that were discussed in part 1 relating to credit events. However, they don&#8217;t affect the way credit default swaps are traded as fundamentally as item 1, and are arguably more boring, so we&#8217;ll start with item 1.</p>
<p><strong>The Non-Standard Nature of Credit Default Swaps Previously</strong></p>
<p>If I buy 100 IBM shares and then buy 100 more I know that I have a position of 200 IBM shares.  I can go to a broker and sell 200 IBM shares to get rid of (close out) this position.</p>
<p>One of the problems with credit default swaps (CDS) as described in part 1 of this series of articles is that you couldn’t do this.  Every CDS trade was different, and it was consequently difficult to close out positions.</p>
<p>Using the description in part 1, consider the case where I have some senior IBM bonds.  I have bought protection against IBM default using a five year CDS.  Now I decide to sell the bonds and want to close out my CDS.  It’s difficult to do this by selling a five year CDS as described previously.  Even if I can get the bonds being covered, the definition of default, the maturity date and all the premium payment dates to match exactly it’s likely that the premiums to be paid will be different from those on the original CDS.  This means a calculation has to be done for both trades separately at each premium payment date.</p>
<p><strong>Standardization</strong></p>
<p>To address this issue a standard contract has been introduced that has:</p>
<p style="padding-left:30px;"><strong>1.  Standard Maturity Dates</strong></p>
<p style="padding-left:30px;">There are four dates per year, the <a href="http://en.wikipedia.org/wiki/IMM_dates">‘IMM dates’</a> that can be the maturity date of a standard contract: 20th March, 20th June, 20th September, and 20th December.  This means that if today is 5th July 2011 and I want to trade a standard five-year CDS I will normally enter into a contract that ends 20th September 2016.  It won’t be a standard CDS if I insist my maturity date has to be 5th July 2016.</p>
<p style="padding-left:30px;"><strong>2.  Standard Premium Payment Dates</strong></p>
<p style="padding-left:30px;">The same four dates per year are the dates on which premiums are paid (and none other).  As a result three months of premium are paid at every premium payment date.</p>
<p style="padding-left:30px;">Note that the use of IMM dates for CDS maturity and premium payment dates was already common when I wrote part 1 of the article.</p>
<p style="padding-left:30px;"><strong>3.  Standard Premiums</strong></p>
<p style="padding-left:30px;">In North America, standard contracts ONLY have premiums of 100 or 500 basis points per annum (1% or 5%).  In Europe, Asia and elsewhere a wider range of premiums is traded on standard contracts, although this is still restricted.  How this works in practice will be explained in part 3.</p>
<p style="padding-left:30px;"><strong>4.  Payment of Full First Coupon</strong></p>
<p style="padding-left:30px;">Standard contracts pay a ‘full first coupon’.  What this means is that if I buy a CDS midway between the standard premium payment dates I still have to pay a full three months’ worth of premium at the next premium date.  Note that ‘coupon’ here means ‘premium payment’.</p>
<p style="padding-left:30px;">For example, if I enter into a CDS with face value $100m on 5th July 2011 with a premium of 5% I will have to pay 3 months x 5% x 100m on the 20th September.  This is in spite of the fact that I have not been protected against default for the full three months.</p>
<p>Note that for the standard premiums and the payment of full first coupon to work we now have upfront fees for CDS.  Again this will be <a href="http://richnewman.wordpress.com/2011/08/04/a-beginner%e2%80%99s-guide-to-credit-default-swaps-part-3/">explained in more detail in part 3</a>.</p>
<p><strong>Impact of these Changes</strong></p>
<p>What all this means is that we have fewer contract variations in the market.  The last item in particular means that a position in any given contract always pays the same amount at every premium date: we don’t need to make any adjustments for when the contract was traded.</p>
<p>In fact, in terms of the amount paid EVERY contract with the same premium (e.g. 500 bps) pays the same percentage of face value at a premium date, regardless of reference entity.  This clearly simplifies coupon processing.  It also allows us to more easily net positions in credit default swaps in our systems.</p>
<p><strong>Conclusion</strong></p>
<p>One of the major changes in the CDS market since <a href="http://richnewman.wordpress.com/2007/12/09/a-beginners-guide-to-credit-default-swaps/">part 1</a> was written is that contracts have been largely standardized.  More detail on this and other changes will be given in <a href="http://richnewman.wordpress.com/2011/08/04/a-beginner%e2%80%99s-guide-to-credit-default-swaps-part-3/">part 3</a>.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/richnewman.wordpress.com/583/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/richnewman.wordpress.com/583/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/richnewman.wordpress.com/583/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/richnewman.wordpress.com/583/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/richnewman.wordpress.com/583/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/richnewman.wordpress.com/583/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/richnewman.wordpress.com/583/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/richnewman.wordpress.com/583/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/richnewman.wordpress.com/583/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/richnewman.wordpress.com/583/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/richnewman.wordpress.com/583/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/richnewman.wordpress.com/583/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/richnewman.wordpress.com/583/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/richnewman.wordpress.com/583/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=richnewman.wordpress.com&amp;blog=909413&amp;post=583&amp;subd=richnewman&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://richnewman.wordpress.com/2011/07/19/a-beginner%e2%80%99s-guide-to-credit-default-swaps-part-2/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/20ffeb59bba855d0069ee936add87d8b?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Rich</media:title>
		</media:content>
	</item>
		<item>
		<title>A Comparison of Some Dependency Injection Frameworks: Part 7 Spring JavaConfig</title>
		<link>http://richnewman.wordpress.com/2010/05/28/a-comparison-of-some-dependency-injection-frameworks-part-7-spring-javaconfig/</link>
		<comments>http://richnewman.wordpress.com/2010/05/28/a-comparison-of-some-dependency-injection-frameworks-part-7-spring-javaconfig/#comments</comments>
		<pubDate>Fri, 28 May 2010 00:53:46 +0000</pubDate>
		<dc:creator>richnewman</dc:creator>
				<category><![CDATA[Dependency Injection]]></category>
		<category><![CDATA[DI Frameworks]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[JavaConfig]]></category>
		<category><![CDATA[Spring Framework]]></category>
		<category><![CDATA[dependency injection]]></category>
		<category><![CDATA[dependency injection frameworks]]></category>

		<guid isPermaLink="false">http://richnewman.wordpress.com/?p=514</guid>
		<description><![CDATA[Introduction This series of articles is examining a number of dependency injection frameworks.  Part 3 of the series looked at the Spring framework configured with XML.  Part 5 and part 6 looked at Guice.  This article will apply the same tests to the Spring framework but configured in code using the JavaConfig download. Code The [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=richnewman.wordpress.com&amp;blog=909413&amp;post=514&amp;subd=richnewman&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><strong>Introduction</strong></p>
<p>This series of articles is examining a number of dependency injection frameworks.  <a href="http://richnewman.wordpress.com/2010/05/10/a-comparison-of-some-dependency-injection-frameworks-part-3-spring-with-xml-configuration-java/">Part 3 of the series</a> looked at the Spring framework configured with XML.  <a href="http://richnewman.wordpress.com/2010/05/22/a-comparison-of-some-dependency-injection-frameworks-part-5-guice-java/">Part 5</a> and <a href="http://richnewman.wordpress.com/2010/05/22/a-comparison-of-some-dependency-injection-frameworks-part-6-guice-java-continued/">part 6</a> looked at Guice.  This article will apply the same tests to the Spring framework but configured in code using the <a href="http://www.springsource.org/javaconfig">JavaConfig download</a>.</p>
<p><strong>Code</strong></p>
<p><a href="http://www.richnewman.plus.com/MovieFinderTestJavaConfig.zip">The code for this article is available.</a></p>
<p>Note that <a href="http://www.springsource.org/javaconfig">JavaConfig used to be a separate download</a> but is now being folded into <a href="http://www.springsource.org/download">core Spring</a> (in Spring 3.0 and later versions).  However for this article I used the separate download version and Spring 2.2. </p>
<p><strong>JavaConfig</strong></p>
<p>Spring JavaConfig is very similar to Spring XML except that all configuration is done in code rather than using XML.  The syntax for retrieving objects from a configured container is identical to Spring XML.</p>
<p>Specifically configuration is done by <a href="http://richnewman.wordpress.com/dependency-injection-code-pages/applicationconfig-class-spring-javaconfig/">writing a class and annotating it with the @Configuration annotation</a>.   We then configure individual objects by writing methods within the class.  We make the methods return the object we require, usually by just instantiating it with the &#8216;new&#8217; keyword.  Then we annotate the method with the @Bean annotation:</p>
<pre><span style="font-family:Courier;color:#646464;font-size:x-small;">@Configuration</span>
<strong><span style="font-family:Courier;color:#7f0055;font-size:x-small;">public</span></strong><span style="font-family:Courier;color:black;font-size:x-small;"> </span><strong><span style="font-family:Courier;color:#7f0055;font-size:x-small;">class</span></strong><span style="font-family:Courier;color:black;font-size:x-small;"> ApplicationConfig {</span>
<span style="font-family:Courier;color:black;font-size:x-small;">      </span><span style="font-family:Courier;color:#646464;font-size:x-small;">@Bean</span>
<span style="font-family:Courier;color:black;font-size:x-small;">      </span><strong><span style="font-family:Courier;color:#7f0055;font-size:x-small;">public</span></strong><span style="font-family:Courier;color:black;font-size:x-small;"> Movie AndreiRublevMovie() {</span>
<span style="font-family:Courier;color:black;font-size:x-small;">            </span><strong><span style="font-family:Courier;color:#7f0055;font-size:x-small;">return</span></strong><span style="font-family:Courier;color:black;font-size:x-small;"> </span><strong><span style="font-family:Courier;color:#7f0055;font-size:x-small;">new</span></strong><span style="font-family:Courier;color:black;font-size:x-small;"> Movie(</span><span style="font-family:Courier;color:#2a00ff;font-size:x-small;">"Andrei Rublev"</span><span style="font-family:Courier;color:black;font-size:x-small;">, </span><span style="font-family:Courier;color:#2a00ff;font-size:x-small;">"Andrei Tarkovsky"</span><span style="font-family:Courier;color:black;font-size:x-small;">);</span>
<span style="font-family:Courier;color:black;font-size:x-small;">      }</span></pre>
<p>The effect of this is identical to configuring a bean in XML in Spring XML.  The method name in JavaConfig (AndreiRublevMovie) corresponds to the ID of the object in Spring XML.  As we shall see, the various techniques for configuring beans in Spring XML are also available in JavaConfig.</p>
<p>We configure our container with a different application context and a constructor that takes the name of the configuration class (or classes):</p>
<pre><span style="font-family:Courier;color:black;font-size:x-small;">            JavaConfigApplicationContext context = </span><strong><span style="font-family:Courier;color:#7f0055;font-size:x-small;">new</span></strong><span style="font-family:Courier;color:black;font-size:x-small;"> JavaConfigApplicationContext(ApplicationConfig.</span><strong><span style="font-family:Courier;color:#7f0055;font-size:x-small;">class</span></strong><span style="font-family:Courier;color:black;font-size:x-small;">);</span></pre>
<p>We can now retrieve objects from the container using the getBean method and the method name as a (string) identifier as usual:</p>
<pre><span style="font-family:Courier;color:black;font-size:x-small;">            Movie andreiRublev = (Movie) context.getBean(</span><span style="font-family:Courier;color:#2a00ff;font-size:x-small;">"AndreiRublevMovie"</span><span style="font-family:Courier;color:black;font-size:x-small;">);</span></pre>
<p><strong>Testing Spring JavaConfig</strong></p>
<p>JavaConfig uses exactly the same syntax for retrieving and using objects as does Spring XML.  As a result our <a href="http://richnewman.wordpress.com/dependency-injection-code-pages/startup-class-spring-javaconfig/">StartUp class for JavaConfig</a> is almost identical to the <a href="http://richnewman.wordpress.com/dependency-injection-code-pages/startup-class-spring-net/">StartUp class for Spring XML</a>.  The only difference is the application context creation described above.</p>
<p>So the only code differences between the tests for Spring XML and JavaConfig are in <a href="http://richnewman.wordpress.com/dependency-injection-code-pages/applicationconfig-class-spring-javaconfig/">the way the container is configured</a>.  As you can see this is very straightforward.</p>
<p>I&#8217;m not going to go through the configuration for all the tests as a result. </p>
<p>Note that:</p>
<ul>
<li>For tests 2 and 3 it&#8217;s very easy to define different objects to be injected into the same class in different circumstances: you just instantiate two instances of the class in different methods and give them the dependent objects as shown below, where simpleMovieFinder and colonDelimitedMovieFinder are configuration methods that return the appropriate MovieFinder objects.</li>
<li>For tests 4 and 5, to specify singleton or prototype scope you just add the &#8216;scope&#8217; annotation (the default is singleton).  This is also shown below.</li>
</ul>
<pre><span style="font-family:Courier;color:black;font-size:x-small;">      </span><span style="font-family:Courier;color:#646464;font-size:x-small;">@Bean</span><span style="font-family:Courier;color:black;font-size:x-small;">(scope=DefaultScopes.</span><em><span style="font-family:Courier;color:#0000c0;font-size:x-small;">SINGLETON</span></em><span style="font-family:Courier;color:black;font-size:x-small;">)</span>
<span style="font-family:Courier;color:black;font-size:x-small;">      </span><strong><span style="font-family:Courier;color:#7f0055;font-size:x-small;">public</span></strong><span style="font-family:Courier;color:black;font-size:x-small;"> MovieLister simpleMovieLister() {</span>
<span style="font-family:Courier;color:black;font-size:x-small;">            </span><strong><span style="font-family:Courier;color:#7f0055;font-size:x-small;">return</span></strong><span style="font-family:Courier;color:black;font-size:x-small;"> </span><strong><span style="font-family:Courier;color:#7f0055;font-size:x-small;">new</span></strong><span style="font-family:Courier;color:black;font-size:x-small;"> MovieLister(simpleMovieFinder());</span>
<span style="font-family:Courier;color:black;font-size:x-small;">      }</span>
<span style="font-family:Courier;color:black;font-size:x-small;">      </span>
<span style="font-family:Courier;color:black;font-size:x-small;">      </span><span style="font-family:Courier;color:#646464;font-size:x-small;">@Bean</span><span style="font-family:Courier;color:black;font-size:x-small;">(scope=DefaultScopes.</span><em><span style="font-family:Courier;color:#0000c0;font-size:x-small;">PROTOTYPE</span></em><span style="font-family:Courier;color:black;font-size:x-small;">)</span>
<span style="font-family:Courier;color:black;font-size:x-small;">      </span><strong><span style="font-family:Courier;color:#7f0055;font-size:x-small;">public</span></strong><span style="font-family:Courier;color:black;font-size:x-small;"> MovieLister colonDelimitedMovieLister() {</span>
<span style="font-family:Courier;color:black;font-size:x-small;">            </span><strong><span style="font-family:Courier;color:#7f0055;font-size:x-small;">return</span></strong><span style="font-family:Courier;color:black;font-size:x-small;"> </span><strong><span style="font-family:Courier;color:#7f0055;font-size:x-small;">new</span></strong><span style="font-family:Courier;color:black;font-size:x-small;"> MovieLister(colonDelimitedMovieFinder());</span>
<span style="font-family:Courier;color:black;font-size:x-small;">      }</span></pre>
<ul>
<li>For test 6, to use a factory method to create a class is again intuitive and simple.  You just create the factory in one configuration method and then call the factory method on it directly where you want your object returned in a second configuration method:</li>
</ul>
<pre><span style="font-family:Courier;color:black;font-size:x-small;">      </span><span style="font-family:Courier;color:#646464;font-size:x-small;">@Bean</span><span style="font-family:Courier;color:black;font-size:x-small;">(scope=DefaultScopes.</span><em><span style="font-family:Courier;color:#0000c0;font-size:x-small;">PROTOTYPE</span></em><span style="font-family:Courier;color:black;font-size:x-small;">)</span>
<span style="font-family:Courier;color:black;font-size:x-small;">      </span><strong><span style="font-family:Courier;color:#7f0055;font-size:x-small;">public</span></strong><span style="font-family:Courier;color:black;font-size:x-small;"> ComplexMovieListerFactory complexMovieListerFactory() {</span>
<span style="font-family:Courier;color:black;font-size:x-small;">            </span><strong><span style="font-family:Courier;color:#7f0055;font-size:x-small;">return</span></strong><span style="font-family:Courier;color:black;font-size:x-small;"> </span><strong><span style="font-family:Courier;color:#7f0055;font-size:x-small;">new</span></strong><span style="font-family:Courier;color:black;font-size:x-small;"> ComplexMovieListerFactory();</span>
<span style="font-family:Courier;color:black;font-size:x-small;">      }</span>
<span style="font-family:Courier;color:black;font-size:x-small;">      </span>
<span style="font-family:Courier;color:black;font-size:x-small;">      </span><span style="font-family:Courier;color:#646464;font-size:x-small;">@Bean</span><span style="font-family:Courier;color:black;font-size:x-small;">(scope=DefaultScopes.</span><em><span style="font-family:Courier;color:#0000c0;font-size:x-small;">PROTOTYPE</span></em><span style="font-family:Courier;color:black;font-size:x-small;">)</span>
<span style="font-family:Courier;color:black;font-size:x-small;">      </span><strong><span style="font-family:Courier;color:#7f0055;font-size:x-small;">public</span></strong><span style="font-family:Courier;color:black;font-size:x-small;"> MovieLister complexMovieLister() {</span>
<span style="font-family:Courier;color:black;font-size:x-small;">            </span><strong><span style="font-family:Courier;color:#7f0055;font-size:x-small;">return</span></strong><span style="font-family:Courier;color:black;font-size:x-small;"> complexMovieListerFactory().build();</span>
<span style="font-family:Courier;color:black;font-size:x-small;">      }</span></pre>
<p><strong>Comments</strong></p>
<p>JavaConfig does seem a step forward compared to the XML configuration problems we have previously been wrestling with for dependency injection.  In  particular it has the following advantages:</p>
<ul>
<li>There is no XML, and the configuration in code means that there is some level of compile-type checking.  However, you can (and usually do) use string identifiers to retrieve objects, so there is still scope for typos that won&#8217;t manifest themselves until runtime.   Note that it is possible to retrieve objects from the container by type to avoid this.</li>
<li>There is no need for code changes in classes (no annotations are applied to the classes you are injecting or injecting into)</li>
<li>The configuration class is very simple, and uses syntax familiar to any developer.  Unlike any other framework here you&#8217;re not being compelled to learn something radically different to use JavaConfig.  All you have to learn is how the few attributes you need are used.</li>
<li>We&#8217;re configuring in code using usual Java syntax.   This makes some of the constructs we have special syntax for in other frameworks seem very odd and cumbersome.  In particular the factory test above almost seems silly: we get our object by returning it from a method, obviously we can do that by just instantiating it OR by instantiating another class that will build it and return it from a build method.</li>
</ul>
<p>JavaConfig is so simple that it makes you wonder why you need a framework at all.  Previously in this series of articles I&#8217;ve suggested that the tests may be a little more advanced than you&#8217;d actually use in practice.  But apart from tests 3 and 4 (singleton and prototype creation) none of the tests really need the Spring framework at all now we&#8217;re using JavaConfig.  We could take all the attributes out and just use the ApplicationConfig class as a factory class.  Even tests 3 and 4 could easily be coded without the framework.  More on this later.</p>
<p><strong>Conclusion</strong></p>
<p>Code configuration as used in JavaConfig seems a simple and intuitive alternative to the more usual XML configuration.</p>
<p>Part 8 of this series will look at Microsoft&#8217;s Unity framework.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/richnewman.wordpress.com/514/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/richnewman.wordpress.com/514/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/richnewman.wordpress.com/514/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/richnewman.wordpress.com/514/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/richnewman.wordpress.com/514/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/richnewman.wordpress.com/514/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/richnewman.wordpress.com/514/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/richnewman.wordpress.com/514/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/richnewman.wordpress.com/514/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/richnewman.wordpress.com/514/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/richnewman.wordpress.com/514/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/richnewman.wordpress.com/514/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/richnewman.wordpress.com/514/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/richnewman.wordpress.com/514/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=richnewman.wordpress.com&amp;blog=909413&amp;post=514&amp;subd=richnewman&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://richnewman.wordpress.com/2010/05/28/a-comparison-of-some-dependency-injection-frameworks-part-7-spring-javaconfig/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/20ffeb59bba855d0069ee936add87d8b?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Rich</media:title>
		</media:content>
	</item>
		<item>
		<title>A Comparison of Some Dependency Injection Frameworks: Part 6 Guice (Java) Continued</title>
		<link>http://richnewman.wordpress.com/2010/05/22/a-comparison-of-some-dependency-injection-frameworks-part-6-guice-java-continued/</link>
		<comments>http://richnewman.wordpress.com/2010/05/22/a-comparison-of-some-dependency-injection-frameworks-part-6-guice-java-continued/#comments</comments>
		<pubDate>Sat, 22 May 2010 14:44:25 +0000</pubDate>
		<dc:creator>richnewman</dc:creator>
				<category><![CDATA[Dependency Inversion]]></category>
		<category><![CDATA[DI Frameworks]]></category>
		<category><![CDATA[Guice]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[dependency injection]]></category>
		<category><![CDATA[dependency injection frameworks]]></category>
		<category><![CDATA[google]]></category>
		<category><![CDATA[guice]]></category>

		<guid isPermaLink="false">http://richnewman.wordpress.com/?p=446</guid>
		<description><![CDATA[Introduction Part 5 of this series of articles started examining Guice as a dependency injection framework.  This article completes that, and makes some general comments on the Guice framework. The code for this article is available (it&#8217;s the same code as in part 5). Testing Guice (Continued) Tests 4 and 5:  Creation of an object with singleton [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=richnewman.wordpress.com&amp;blog=909413&amp;post=446&amp;subd=richnewman&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><strong>Introduction</strong></p>
<p><a href="http://richnewman.wordpress.com/2010/05/22/a-comparison-of-some-dependency-injection-frameworks-part-5-guice-java/">Part 5 of this series of articles</a> started examining Guice as a dependency injection framework.  This article completes that, and makes some general comments on the <a href="http://code.google.com/p/google-guice/">Guice framework</a>.</p>
<p><a href="http://www.richnewman.plus.com/MovieFinderTestGuice.zip">The code for this article is available</a> (it&#8217;s the same code as in part 5).</p>
<p><strong>Testing Guice (Continued)</strong></p>
<p><strong><em>Tests 4 and 5:  Creation of an object with singleton scope, creation of an object with prototype scope</em></strong></p>
<p>As before we run tests 4 and 5 by making the MovieLister class from test 2 have singleton scope, and the MovieLister from test 3 have prototype scope.  We do this in the private module configuration classes set up in test 3.</p>
<p>The syntax for specifying that a class is a singleton is straightforward, and can be seen in the <a href="http://richnewman.wordpress.com/simplemovielisterprivatemodule-class-net/">SimpleMovieListerPrivateModule</a> class:</p>
<pre><span style="font-family:Courier;color:black;font-size:x-small;">            bind(MovieLister.</span><strong><span style="font-family:Courier;color:#7f0055;font-size:x-small;">class</span></strong><span style="font-family:Courier;color:black;font-size:x-small;">)</span>
<span style="font-family:Courier;color:black;font-size:x-small;">            .annotatedWith(</span><span style="font-family:Courier;color:#646464;font-size:x-small;">Simple</span><span style="font-family:Courier;color:black;font-size:x-small;">.</span><strong><span style="font-family:Courier;color:#7f0055;font-size:x-small;">class</span></strong><span style="font-family:Courier;color:black;font-size:x-small;">)</span>
<span style="font-family:Courier;color:black;font-size:x-small;">            .to(MovieLister.</span><strong><span style="font-family:Courier;color:#7f0055;font-size:x-small;">class</span></strong><span style="font-family:Courier;color:black;font-size:x-small;">)</span>
<span style="font-family:Courier;color:black;font-size:x-small;">            .in(</span><span style="font-family:Courier;color:#646464;font-size:x-small;">Singleton</span><span style="font-family:Courier;color:black;font-size:x-small;">.</span><strong><span style="font-family:Courier;color:#7f0055;font-size:x-small;">class</span></strong><span style="font-family:Courier;color:black;font-size:x-small;">);</span></pre>
<p>Note that we&#8217;ve just added the simple syntax &#8216;.in(Singleton.class)&#8217; to our binding to specify the singleton.</p>
<p>The default scope is prototype here, so in the <a href="http://richnewman.wordpress.com/colondelimitedmovielisterprivatemodule-class-net/">ColonDelimitedMovieListerPrivate</a> module class we don&#8217;t need to do anything special.  So if we make the simple singleton change above the tests pass.</p>
<p><strong><em>Test 6: Use of a factory class and method to create a dependent object.</em></strong></p>
<p>Test 6 is intended to test our ability to use code (in a different) class to generate the object we require when we request it from the container.  Here we want to return a MovieLister from a factory class.</p>
<p>In Guice you can do this with a &#8216;provider&#8217;: the provider is the equivalent of the factory from earlier Spring examples.  For our test we write a <a href="http://richnewman.wordpress.com/dependency-injection-code-pages/complexmovielisterfactory-class-guice-java/">class that implements the Provider&lt;MovieLister&gt; interface</a>.  As you can see this interface has a &#8216;get&#8217; method that returns a MovieLister, which is our factory method.</p>
<p>We need to bind this so that when we request a MovieLister our factory method gets called.  To do this we put the binding code below into our main module (configuration) class:</p>
<pre><span style="font-family:Courier;color:black;font-size:x-small;">            bind(MovieLister.</span><strong><span style="font-family:Courier;color:#7f0055;font-size:x-small;">class</span></strong><span style="font-family:Courier;color:black;font-size:x-small;">)</span>
<span style="font-family:Courier;color:black;font-size:x-small;">            .annotatedWith(</span><span style="font-family:Courier;color:#646464;font-size:x-small;">Complex</span><span style="font-family:Courier;color:black;font-size:x-small;">.</span><strong><span style="font-family:Courier;color:#7f0055;font-size:x-small;">class</span></strong><span style="font-family:Courier;color:black;font-size:x-small;">)</span>
<span style="font-family:Courier;color:black;font-size:x-small;">            .toProvider(ComplexMovieListerFactory.</span><strong><span style="font-family:Courier;color:#7f0055;font-size:x-small;">class</span></strong><span style="font-family:Courier;color:black;font-size:x-small;">);</span></pre>
<p>Note that we need an annotation because we already have other configurations that return type MovieLister from the container.  Now if we request an object from the container with the MovieLister/Complex key as below Guice will run the get method on our ComplexMovieListerFactory and return the result, which is what we want:</p>
<pre><span style="font-family:Courier;color:black;font-size:x-small;">            MovieLister complexLister = guiceInjector.getInstance(Key.<em>get</em>(MovieLister.</span><strong><span style="font-family:Courier;color:#7f0055;font-size:x-small;">class</span></strong><span style="font-family:Courier;color:black;font-size:x-small;">, </span><span style="font-family:Courier;color:#646464;font-size:x-small;">Complex</span><span style="font-family:Courier;color:black;font-size:x-small;">.</span><strong><span style="font-family:Courier;color:#7f0055;font-size:x-small;">class</span></strong><span style="font-family:Courier;color:black;font-size:x-small;">));</span>
<span style="font-family:Courier;color:black;font-size:x-small;">            Movie[] tarkovskyMovies = complexLister.moviesDirectedBy(</span><span style="font-family:Courier;color:#2a00ff;font-size:x-small;">"Andrei Tarkovsky"</span><span style="font-family:Courier;color:black;font-size:x-small;">);</span>
<span style="font-family:Courier;color:black;font-size:x-small;">            </span><strong><span style="font-family:Courier;color:#7f0055;font-size:x-small;">for</span></strong><span style="font-family:Courier;color:black;font-size:x-small;">(Movie movie : tarkovskyMovies){</span>
<span style="font-family:Courier;color:black;font-size:x-small;">                  System.</span><em><span style="font-family:Courier;color:#0000c0;font-size:x-small;">out</span></em><span style="font-family:Courier;color:black;font-size:x-small;">.println(movie.toString());</span></pre>
<p>Whilst this isn&#8217;t particularly complex it is quite a different approach to the configuration approaches we&#8217;ve already seen in Guice: now we&#8217;re implementing an interface to get Guice to configure an object.</p>
<p><strong><em>Test 7: Injection of the container itself (so it can be used to retrieve objects).</em></strong></p>
<p>The code for this again is in the <a href="http://richnewman.wordpress.com/dependency-injection-code-pages/complexmovielisterfactory-class-guice-java/">ComplexMovieListerFactory class</a>.  Here Guice is actually simpler than Spring, since it doesn&#8217;t require implementation of a specific interface to inject the container.  You simply use the usual syntax in your class: here we write a constructor with the appropriate signature to take the container, and mark that constructor with the @Inject attribute:</p>
<pre><strong><span style="font-family:Courier;color:#7f0055;font-size:x-small;">public</span></strong><span style="font-family:Courier;color:black;font-size:x-small;"> </span><strong><span style="font-family:Courier;color:#7f0055;font-size:x-small;">class</span></strong><span style="font-family:Courier;color:black;font-size:x-small;"> ComplexMovieListerFactory </span><strong><span style="font-family:Courier;color:#7f0055;font-size:x-small;">implements</span></strong><span style="font-family:Courier;color:black;font-size:x-small;"> Provider&lt;MovieLister&gt; {</span>
<span style="font-family:Courier;color:black;font-size:x-small;">      </span>
<span style="font-family:Courier;color:black;font-size:x-small;">      </span><strong><span style="font-family:Courier;color:#7f0055;font-size:x-small;">private</span></strong><span style="font-family:Courier;color:black;font-size:x-small;"> Injector </span><span style="font-family:Courier;color:#0000c0;font-size:x-small;">injector</span><span style="font-family:Courier;color:black;font-size:x-small;">;</span>
<span style="font-family:Courier;color:black;font-size:x-small;">      </span>
<span style="font-family:Courier;color:black;font-size:x-small;">      </span><span style="font-family:Courier;color:#646464;font-size:x-small;">@Inject</span>
<span style="font-family:Courier;color:black;font-size:x-small;">      </span><strong><span style="font-family:Courier;color:#7f0055;font-size:x-small;">public</span></strong><span style="font-family:Courier;color:black;font-size:x-small;"> ComplexMovieListerFactory(Injector injector) {</span>
<span style="font-family:Courier;color:black;font-size:x-small;">            </span><strong><span style="font-family:Courier;color:#7f0055;font-size:x-small;">this</span></strong><span style="font-family:Courier;color:black;font-size:x-small;">.</span><span style="font-family:Courier;color:#0000c0;font-size:x-small;">injector</span><span style="font-family:Courier;color:black;font-size:x-small;"> = injector;</span>
<span style="font-family:Courier;color:black;font-size:x-small;">      }</span>
<span style="font-family:Courier;color:black;font-size:x-small;">...</span></pre>
<p>The rest of the <a href="http://richnewman.wordpress.com/dependency-injection-code-pages/complexmovielisterfactory-class-guice-java/">ComplexMovieListerFactory</a> class is fairly self-explanatory.  One thing to note is that (as far as I can see) the Guice container has no equivalent of Spring&#8217;s &#8216;getBeansOfType&#8217; method, so we&#8217;re having to retrieve the Movie objects individually from the container.  My feeling is this is not really important as this is a little unrealistic: in practice: we&#8217;d be unlikely to want to retrieve instances of all objects in the container of a given type.</p>
<p><strong>Comments on Guice</strong></p>
<p>Guice is directly trying to deal with some of the problems with XML configuration I outlined in the first article in this series.  In particular it&#8217;s trying to remove those incomprehensible runtime errors you can get if  you your XML configuration is wrong.</p>
<p>For simple injection scenarios it does seem like a step forward.  However, I find Guice quite hard to like (and when I started this analysis I really wanted to like it).</p>
<ul>
<li>There are several different ways of configuring an object.  As you can see from the length of this article and part 5, this can get quite confusing and difficult.  You have to learn and understand the different scenarios to be able to use the framework.</li>
<li>The different configuration methods are used in different circumstances depending on the complexity of the configuration scenario.  As we have seen, this can include changing the configuration for an existing object when a new object of the same type needs to be configured.  Again you have to understand and be able to handle this. </li>
<li>For any moderately complex injection scenario you are having to change the code of your classes by annotating them.  This effectively means we have construction logic back in our code classes, albeit in a limited way and in the form of metadata rather than actual code.</li>
<li>The code in the configuration classes isn&#8217;t particularly intuitive.  In particular the use of private modules for the solution to the so-called &#8216;robot legs&#8217; problem leads to quite complex code.</li>
</ul>
<p>Overall my feeling is that Guice does address some of the issues with XML configuration that we see in frameworks like Spring.  However it then introduces a number of issues of its own.  Obviously I have tested with some reasonably advanced scenarios here.  Some of these may not need to be used that frequently in real production code. I haven&#8217;t personally used Guice on any real life project.  But on the basis of this analysis I think I would be reluctant to attempt to do so.</p>
<p><strong>Conclusion</strong></p>
<p>Guice was the most disappointing framework I looked at.  Its design goals are explicitly to solve some of the problems with XML configuration discussed in part 1 of this series of articles.  However, it seems to me it does this in a way that only works well in very simple dependency injection scenarios.  As soon as there is a moderate level of complexity the developer is having to learn several different configuration techniques, some of which aren&#8217;t easy to use, and how to apply them.</p>
<p><a href="http://richnewman.wordpress.com/2010/05/28/a-comparison-of-some-dependency-injection-frameworks-part-7-spring-javaconfig/">Part 7 will look at Spring JavaConfig</a>.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/richnewman.wordpress.com/446/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/richnewman.wordpress.com/446/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/richnewman.wordpress.com/446/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/richnewman.wordpress.com/446/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/richnewman.wordpress.com/446/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/richnewman.wordpress.com/446/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/richnewman.wordpress.com/446/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/richnewman.wordpress.com/446/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/richnewman.wordpress.com/446/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/richnewman.wordpress.com/446/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/richnewman.wordpress.com/446/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/richnewman.wordpress.com/446/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/richnewman.wordpress.com/446/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/richnewman.wordpress.com/446/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=richnewman.wordpress.com&amp;blog=909413&amp;post=446&amp;subd=richnewman&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://richnewman.wordpress.com/2010/05/22/a-comparison-of-some-dependency-injection-frameworks-part-6-guice-java-continued/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/20ffeb59bba855d0069ee936add87d8b?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Rich</media:title>
		</media:content>
	</item>
		<item>
		<title>A Comparison of Some Dependency Injection Frameworks: Part 5 Guice (Java)</title>
		<link>http://richnewman.wordpress.com/2010/05/22/a-comparison-of-some-dependency-injection-frameworks-part-5-guice-java/</link>
		<comments>http://richnewman.wordpress.com/2010/05/22/a-comparison-of-some-dependency-injection-frameworks-part-5-guice-java/#comments</comments>
		<pubDate>Sat, 22 May 2010 08:08:53 +0000</pubDate>
		<dc:creator>richnewman</dc:creator>
				<category><![CDATA[Dependency Injection]]></category>
		<category><![CDATA[DI Frameworks]]></category>
		<category><![CDATA[Guice]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[dependency injection]]></category>
		<category><![CDATA[dependency injection frameworks]]></category>
		<category><![CDATA[google]]></category>
		<category><![CDATA[guice]]></category>

		<guid isPermaLink="false">http://richnewman.wordpress.com/?p=409</guid>
		<description><![CDATA[Introduction This series of articles compares a number of dependency injection frameworks. Part 4 looked at Spring.Net.  This article and part 6 look at Google&#8217;s Guice framework. Guice Guice is a valiant attempt by those clever guys at Google to make dependency injection simpler, and to remove some of the problems with XML configuration described in [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=richnewman.wordpress.com&amp;blog=909413&amp;post=409&amp;subd=richnewman&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><strong>Introduction</strong></p>
<p>This series of articles compares a number of dependency injection frameworks. <a href="http://richnewman.wordpress.com/2010/05/15/a-comparison-of-some-dependency-injection-frameworks-part-4-spring-net-with-xml-configuration-net/">Part 4 looked at Spring.Net</a>.  This article and part 6 look at <a href="http://code.google.com/p/google-guice/">Google&#8217;s Guice framework</a>.</p>
<p><strong>Guice</strong></p>
<p>Guice is a valiant attempt by those clever guys at Google to make dependency injection simpler, and to remove some of the problems with XML configuration described in part one of this series.  In the Guice framework:</p>
<ul>
<li>All configuration is done in code.  There is no undebuggable XML.  Configuration is typically done in standard Java classes that extend Guice&#8217;s AbstractModule base class.</li>
<li>Where only one configuration of a class is needed in a program the sole instance can be injected by type.  (This is like autowiring in Spring). </li>
<li>If more than one configuration of a class is needed Java annotations (plus the type) are used to identify the different configurations.  The annotations are applied in the code at the point where the object is injected.  We&#8217;ll see  how this works in a moment, but it means we no longer need string identifiers for objects.</li>
<li>Where the annotation approach is not powerful enough other techniques may need to be used.  As we shall see these techniques include using providers, and using private modules.</li>
</ul>
<p>All of this allows our compiler to check for most configuration problems at compile time.  In particular runtime errors from string identifiers being misspelt, or the wrong type being injected, should disappear.</p>
<p>This seems promising.  Let&#8217;s see how we can handle our tests.</p>
<p><strong>Code</strong></p>
<p><a href="http://www.richnewman.plus.com/MovieFinderTestGuice.zip">The full code for this example is available</a>.  As you can see, it ends up having significantly more code files than the code for the other frameworks examined in this series of articles.  In particular there are a number of annotation interfaces (Simple, ColonDelimited, Complex and AndreiRublev).  Most of our basic classes for the example remain the same (<a href="http://richnewman.wordpress.com/movie-class-java/">Movie</a>, <a href="http://richnewman.wordpress.com/simplemoviefinder-class-java/">SimpleMovieFinder</a>, <a href="http://richnewman.wordpress.com/colondelimitedmoviefinder-class-java/">ColonDelimitedMovieFinder</a>, <a href="http://richnewman.wordpress.com/complexmoviefinder-class-java/">ComplexMovieFinder</a>, <a href="http://richnewman.wordpress.com/movielister-class-java/">MovieLister</a> etc.).  However, the MovieLister class now has an &#8216;@Inject&#8217; annotation applied to the constructor that is used to inject the MovieFinder. </p>
<p><strong><strong>Testing Guice</strong></strong></p>
<p>We again go through our tests in some detail as this illustrates how Guice works.</p>
<p><strong><em>Test 1: Configuration and retrieval of an object with (only) string dependencies</em></strong> </p>
<p>As mentioned above, in Guice we can configure an object <a href="http://richnewman.wordpress.com/guice-movielistermodule-configuration-class/">by inheriting from Guice&#8217;s AbstractModule class</a>, and overriding the configure method.  We can configure our single object with string dependencies either by type alone, or by type plus an annotation.</p>
<p><span style="text-decoration:underline;">(i) Configuration by type alone</span></p>
<p>Our configuration class (&#8216;module&#8217;) is set up as below:</p>
<pre><strong><span style="font-family:Courier;color:#7f0055;font-size:x-small;">public</span></strong><span style="font-family:Courier;color:black;font-size:x-small;"> </span><strong><span style="font-family:Courier;color:#7f0055;font-size:x-small;">class</span></strong><span style="font-family:Courier;color:black;font-size:x-small;"> MovieListerModule </span><strong><span style="font-family:Courier;color:#7f0055;font-size:x-small;">extends</span></strong><span style="font-family:Courier;color:black;font-size:x-small;"> AbstractModule {</span>

<span style="font-family:Courier;color:black;font-size:x-small;">      </span><span style="font-family:Courier;color:#646464;font-size:x-small;">@Override</span>
<span style="font-family:Courier;color:black;font-size:x-small;">      </span><strong><span style="font-family:Courier;color:#7f0055;font-size:x-small;">protected</span></strong><span style="font-family:Courier;color:black;font-size:x-small;"> </span><strong><span style="font-family:Courier;color:#7f0055;font-size:x-small;">void</span></strong><span style="font-family:Courier;color:black;font-size:x-small;"> configure() {</span>
<span style="font-family:Courier;color:black;font-size:x-small;">            bind(Movie.</span><strong><span style="font-family:Courier;color:#7f0055;font-size:x-small;">class</span></strong><span style="font-family:Courier;color:black;font-size:x-small;">)</span>
<span style="font-family:Courier;color:black;font-size:x-small;">            .toInstance(</span><strong><span style="font-family:Courier;color:#7f0055;font-size:x-small;">new</span></strong><span style="font-family:Courier;color:black;font-size:x-small;"> Movie(</span><span style="font-family:Courier;color:#2a00ff;font-size:x-small;">"The Sacrifice"</span><span style="font-family:Courier;color:black;font-size:x-small;">, </span><span style="font-family:Courier;color:#2a00ff;font-size:x-small;">"Andrei Tarkovsky"</span><span style="font-family:Courier;color:black;font-size:x-small;">));</span></pre>
<p>This says that if the code just requests an object of type Movie (without annotating the request) then a Movie Object with name &#8216;The Sacrifice&#8217; will be returned.</p>
<p>We can request instances of these objects directly from the container using the syntax below.  Firstly we need to configure the container and retrieve an instance of it (as we do with other frameworks).  Here we are configuring the container with the configuration &#8216;module&#8217; classes we need.  MovieListerModule is shown above, the other modules we shall see later:</p>
<pre><span style="font-family:Courier;color:black;font-size:x-small;">            Injector guiceInjector = Guice.<em>createInjector</em>(</span><strong><span style="font-family:Courier;color:#7f0055;font-size:x-small;">new</span></strong><span style="font-family:Courier;color:black;font-size:x-small;"> MovieListerModule(), </span><strong><span style="font-family:Courier;color:#7f0055;font-size:x-small;">new</span></strong><span style="font-family:Courier;color:black;font-size:x-small;"> SimpleMovieListerPrivateModule(), </span><strong><span style="font-family:Courier;color:#7f0055;font-size:x-small;">new</span></strong><span style="font-family:Courier;color:black;font-size:x-small;"> ColonDelimitedMovieListerPrivateModule());</span></pre>
<p>Then we request our object by type alone:</p>
<pre><span style="font-family:Courier;color:black;font-size:x-small;">            Movie andreiRublevMovie2 = guiceInjector.getInstance(Movie.</span><strong><span style="font-family:Courier;color:#7f0055;font-size:x-small;">class</span></strong><span style="font-family:Courier;color:black;font-size:x-small;">);</span>
<span style="font-family:Courier;color:black;font-size:x-small;">            System.</span><em><span style="font-family:Courier;color:#0000c0;font-size:x-small;">out</span></em><span style="font-family:Courier;color:black;font-size:x-small;">.println(andreiRublevMovie2.toString());</span></pre>
<p><span style="text-decoration:underline;">(ii) Configuration by type plus an annotation</span></p>
<p>The syntax above begs the question of how we configure a different Movie object to be injected elsewhere in our code.  The &#8216;binding&#8217; to the Movie type alone is already used.  The answer is that we can create a key for our configuration based on the type (Movie) plus an annotation.  We can then configure an object and associate the configuration with the key, and retrieve the object from the container using the key.</p>
<p>To configure an object with a two-part key of this kind we put the code below in our MovieListerModule configuration class.  Here &#8216;AndreiRublev&#8217; is an annotation defined elsewhere in our code:</p>
<pre><span style="font-family:Courier;color:black;font-size:x-small;">            bind(Movie.</span><strong><span style="font-family:Courier;color:#7f0055;font-size:x-small;">class</span></strong><span style="font-family:Courier;color:black;font-size:x-small;">)</span>
<span style="font-family:Courier;color:black;font-size:x-small;">            .annotatedWith(</span><span style="font-family:Courier;color:#646464;font-size:x-small;">AndreiRublev</span><span style="font-family:Courier;color:black;font-size:x-small;">.</span><strong><span style="font-family:Courier;color:#7f0055;font-size:x-small;">class</span></strong><span style="font-family:Courier;color:black;font-size:x-small;">)</span>
<span style="font-family:Courier;color:black;font-size:x-small;">            .toInstance(</span><strong><span style="font-family:Courier;color:#7f0055;font-size:x-small;">new</span></strong><span style="font-family:Courier;color:black;font-size:x-small;"> Movie(</span><span style="font-family:Courier;color:#2a00ff;font-size:x-small;">"Andrei Rublev"</span><span style="font-family:Courier;color:black;font-size:x-small;">, </span><span style="font-family:Courier;color:#2a00ff;font-size:x-small;">"Andrei Tarkovsky"</span><span style="font-family:Courier;color:black;font-size:x-small;">));</span></pre>
<p>We can then request this object from the container using the key:</p>
<pre><span style="font-family:Courier;color:black;font-size:x-small;">            Movie andreiRublevMovie = guiceInjector.getInstance(Key.<em>get</em>(Movie.</span><strong><span style="font-family:Courier;color:#7f0055;font-size:x-small;">class</span></strong><span style="font-family:Courier;color:black;font-size:x-small;">, </span><span style="font-family:Courier;color:#646464;font-size:x-small;">AndreiRublev</span><span style="font-family:Courier;color:black;font-size:x-small;">.</span><strong><span style="font-family:Courier;color:#7f0055;font-size:x-small;">class</span></strong><span style="font-family:Courier;color:black;font-size:x-small;">));</span>
<span style="font-family:Courier;color:black;font-size:x-small;">            System.</span><em><span style="font-family:Courier;color:#0000c0;font-size:x-small;">out</span></em><span style="font-family:Courier;color:black;font-size:x-small;">.println(andreiRublevMovie.toString());</span></pre>
<p>Here we use Guice&#8217;s Key.get method to retrieve the key.  We then use that key with the getInstance method to retrieve the Andrei Rublev movie object from the container using the configuration shown above.</p>
<p>Note that there are no string identifiers here.  Note also that the getInstance method returns an object with the correct type Movie (because this is the first type passed in as an argument to the key).  This makes type errors much less likely than the equivalent XML approach.</p>
<p><strong><em>Test 2:  Injection of an object into an instance of a class.</em></strong></p>
<p>Our example here is to inject an instance of SimpleMovieFinder into class MovieLister.  Note that MovieLister expects an object of type MovieFinder (an interface) to be injected by constructor injection.</p>
<p>Note that the code shown in this section is <strong>not</strong> in the code sample.  The reasons for this are explained below.</p>
<p>Let&#8217;s look at how we&#8217;d do that using an annotation to try to distinguish different instances of MovieFinder being injected in different places.  To do this we need to configure MovieFinder with an annotation in our configuration class, as described above:</p>
<pre><span style="font-family:Courier;color:black;font-size:x-small;">            bind(MovieFinder.</span><strong><span style="font-family:Courier;color:#7f0055;font-size:x-small;">class</span></strong><span style="font-family:Courier;color:black;font-size:x-small;">)</span>
<span style="font-family:Courier;color:black;font-size:x-small;">            .annotatedWith(</span><span style="font-family:Courier;color:#64acd0;font-size:x-small;">Simple</span><span style="font-family:Courier;color:black;font-size:x-small;">.</span><strong><span style="font-family:Courier;color:#7f0055;font-size:x-small;">class</span></strong><span style="font-family:Courier;color:black;font-size:x-small;">)</span>
<span style="font-family:Courier;color:black;font-size:x-small;">            .to(SimpleMovieFinder.</span><strong><span style="font-family:Courier;color:#7f0055;font-size:x-small;">class</span></strong><span style="font-family:Courier;color:black;font-size:x-small;">);</span></pre>
<p>Now in our MovieLister class itself we can annotate the constructor as below:</p>
<pre><strong><span style="font-family:Courier;color:#7f0055;font-size:x-small;">public</span></strong><span style="font-family:Courier;color:black;font-size:x-small;"> </span><strong><span style="font-family:Courier;color:#7f0055;font-size:x-small;">class</span></strong><span style="font-family:Courier;color:black;font-size:x-small;"> MovieLister {</span>
<span style="font-family:Courier;color:black;font-size:x-small;">      </span>
<span style="font-family:Courier;color:black;font-size:x-small;">      </span><strong><span style="font-family:Courier;color:#7f0055;font-size:x-small;">private</span></strong><span style="font-family:Courier;color:black;font-size:x-small;"> MovieFinder </span><span style="font-family:Courier;color:#0000c0;font-size:x-small;">finder</span><span style="font-family:Courier;color:black;font-size:x-small;">;</span>
<span style="font-family:Courier;color:black;font-size:x-small;">      </span>
<span style="font-family:Courier;color:black;font-size:x-small;">      </span><span style="font-family:Courier;color:#646464;font-size:x-small;">@Inject</span>
<span style="font-family:Courier;color:black;font-size:x-small;">    </span><strong><span style="font-family:Courier;color:#7f0055;font-size:x-small;">public</span></strong><span style="font-family:Courier;color:black;font-size:x-small;"> MovieLister(</span><span style="font-family:Courier;color:#646464;font-size:x-small;">@Simple</span><span style="font-family:Courier;color:black;font-size:x-small;"> MovieFinder finder) {</span>
<span style="font-family:Courier;color:black;font-size:x-small;">            </span><strong><span style="font-family:Courier;color:#7f0055;font-size:x-small;">this</span></strong><span style="font-family:Courier;color:black;font-size:x-small;">.</span><span style="font-family:Courier;color:#0000c0;font-size:x-small;">finder</span><span style="font-family:Courier;color:black;font-size:x-small;"> = finder;</span>
<span style="font-family:Courier;color:black;font-size:x-small;">      }</span></pre>
<p>Here the @Inject annotation tells Guice that it should use this constructor to build this object for the container.  The @Simple annotation, combined with the type MovieFinder, tells Guice to use the binding above.  That is, it tells it that it should instantiate SimpleMovieFinder and inject it here.</p>
<p>We can now configure our container as above, and retrieve the SimpleMovieFinder object from it, and use it, using the usual syntax:</p>
<pre><span style="font-family:Courier;color:black;font-size:x-small;">            MovieLister simpleLister = guiceInjector.getInstance(MovieLister.</span><strong><span style="font-family:Courier;color:#7f0055;font-size:x-small;">class</span></strong><span style="font-family:Courier;color:black;font-size:x-small;">);</span>
<span style="font-family:Courier;color:black;font-size:x-small;">            Movie[] jamesCameronMovies = simpleLister.moviesDirectedBy(</span><span style="font-family:Courier;color:#2a00ff;font-size:x-small;">"James Cameron"</span><span style="font-family:Courier;color:black;font-size:x-small;">);</span>
<span style="font-family:Courier;color:black;font-size:x-small;">            </span><strong><span style="font-family:Courier;color:#7f0055;font-size:x-small;">for</span></strong><span style="font-family:Courier;color:black;font-size:x-small;">(Movie movie : jamesCameronMovies){</span>
<span style="font-family:Courier;color:black;font-size:x-small;">                  System.</span><em><span style="font-family:Courier;color:#0000c0;font-size:x-small;">out</span></em><span style="font-family:Courier;color:black;font-size:x-small;">.println(movie.toString());</span></pre>
<p>This is again fairly straightforward.  However, note that we have had to alter the code file for the SimpleMovieFinder class to get it to work, admittedly only by adding annotations.</p>
<p>However, there is a problem here.  Our next test (test 3) is to inject a different object into MovieLister under different circumstances.  The annotation approach shown here clearly doesn&#8217;t allow this (we can&#8217;t have different annotations in the class in different circumstances).  We have to change our approach (and the code) when we decide we want to use this slightly more complex scenario.  This is the reason the code in the code sample is not as shown above: it has to take account of test 3.</p>
<p><strong><em>Test 3:  Injection of a different object into an instance of the same class as used in test 2.</em></strong></p>
<p>The Guice team have given this scenario a name: the &#8216;robot legs problem&#8217;.  We need a different technique to the standard Guice annotations to deal with it.  The problem and the solution are both described in the &#8216;How do I build two similar but slightly different trees of objects?&#8217; section of <a href="http://code.google.com/p/google-guice/wiki/FrequentlyAskedQuestions">Guice&#8217;s FAQ</a>.</p>
<p>The solution uses private modules (configuration classes). </p>
<p>In short we remove the @Simple annotation in the constructor of MovieLister shown under test 2 above.  Then we have separate configuration classes for the MovieLister that uses SimpleMovieFinder (<a href="http://richnewman.wordpress.com/simplemovielisterprivatemodule-class-net/">SimpleMovieListerPrivateModule</a>), and for the MovieLister that uses ColonDelimitedMovieFinder (<a href="http://richnewman.wordpress.com/colondelimitedmovielisterprivatemodule-class-net/">ColonDelimitedMovieListerPrivateModule</a>). </p>
<p>As you can see, the two private module classes are very similar.  In both cases we bind the MovieFinder type to the class type we are interested in (SimpleMovieFinder or ColonDelimitedMovieFinder).  Since the modules are private we can now inject these by type alone.  We then bind the MovieLister class itself.  We DO need to annotate this binding, because in the client startup code we&#8217;ll need to be able to retrieve the two different MovieListers.  Finally we need to &#8216;expose&#8217; the MovieLister so that Guice knows it is to be used by client code (rather than being private to the module).</p>
<p>We&#8217;ve already seen above how we tell the container to configure itself using all of these module files:</p>
<pre><span style="font-family:Courier;color:black;font-size:x-small;">            Injector guiceInjector = Guice.<em>createInjector</em>(</span><strong><span style="font-family:Courier;color:#7f0055;font-size:x-small;">new</span></strong><span style="font-family:Courier;color:black;font-size:x-small;"> MovieListerModule(), </span><strong><span style="font-family:Courier;color:#7f0055;font-size:x-small;">new</span></strong><span style="font-family:Courier;color:black;font-size:x-small;"> SimpleMovieListerPrivateModule(), </span><strong><span style="font-family:Courier;color:#7f0055;font-size:x-small;">new</span></strong><span style="font-family:Courier;color:black;font-size:x-small;"> ColonDelimitedMovieListerPrivateModule());</span></pre>
<p>Finally we can use the two configurations in the same client code as below.  Note that we are retrieving the two different MovieListers by type plus annotation:</p>
<pre><span style="font-family:Courier;color:black;font-size:x-small;">            MovieLister simpleLister = guiceInjector.getInstance(Key.<em>get</em>(MovieLister.</span><strong><span style="font-family:Courier;color:#7f0055;font-size:x-small;">class</span></strong><span style="font-family:Courier;color:black;font-size:x-small;">, </span><span style="font-family:Courier;color:#646464;font-size:x-small;">Simple</span><span style="font-family:Courier;color:black;font-size:x-small;">.</span><strong><span style="font-family:Courier;color:#7f0055;font-size:x-small;">class</span></strong><span style="font-family:Courier;color:black;font-size:x-small;">));</span>
<span style="font-family:Courier;color:black;font-size:x-small;">            Movie[] jamesCameronMovies = simpleLister.moviesDirectedBy(</span><span style="font-family:Courier;color:#2a00ff;font-size:x-small;">"James Cameron"</span><span style="font-family:Courier;color:black;font-size:x-small;">);</span>
<span style="font-family:Courier;color:black;font-size:x-small;">            </span><strong><span style="font-family:Courier;color:#7f0055;font-size:x-small;">for</span></strong><span style="font-family:Courier;color:black;font-size:x-small;">(Movie movie : jamesCameronMovies){</span>
<span style="font-family:Courier;color:black;font-size:x-small;">                  System.</span><em><span style="font-family:Courier;color:#0000c0;font-size:x-small;">out</span></em><span style="font-family:Courier;color:black;font-size:x-small;">.println(movie.toString());</span>
<span style="font-family:Courier;color:black;font-size:x-small;">            }</span>
<span style="font-family:Courier;color:black;font-size:x-small;">            MovieLister colonDelimitedLister = guiceInjector.getInstance(Key.<em>get</em>(MovieLister.</span><strong><span style="font-family:Courier;color:#7f0055;font-size:x-small;">class</span></strong><span style="font-family:Courier;color:black;font-size:x-small;">, </span><span style="font-family:Courier;color:#646464;font-size:x-small;">ColonDelimited</span><span style="font-family:Courier;color:black;font-size:x-small;">.</span><strong><span style="font-family:Courier;color:#7f0055;font-size:x-small;">class</span></strong><span style="font-family:Courier;color:black;font-size:x-small;">));</span>
<span style="font-family:Courier;color:black;font-size:x-small;">            Movie[] martinScorseseMovies = colonDelimitedLister.moviesDirectedBy(</span><span style="font-family:Courier;color:#2a00ff;font-size:x-small;">"Martin Scorsese"</span><span style="font-family:Courier;color:black;font-size:x-small;">);</span>
<span style="font-family:Courier;color:black;font-size:x-small;">            </span><strong><span style="font-family:Courier;color:#7f0055;font-size:x-small;">for</span></strong><span style="font-family:Courier;color:black;font-size:x-small;">(Movie movie : martinScorseseMovies){</span>
<span style="font-family:Courier;color:black;font-size:x-small;">                  System.</span><em><span style="font-family:Courier;color:#0000c0;font-size:x-small;">out</span></em><span style="font-family:Courier;color:black;font-size:x-small;">.println(movie.toString());</span>
<span style="font-family:Courier;color:black;font-size:x-small;">            }</span></pre>
<p>This is a bit complicated compared to the rather simpler configuration in Spring.</p>
<p><strong>Conclusion</strong></p>
<p>We will look at the remainder of our test cases, and make some general comments on the Guice framework, in <a href="http://richnewman.wordpress.com/2010/05/22/a-comparison-of-some-dependency-injection-frameworks-part-6-guice-java-continued/">part 6</a>.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/richnewman.wordpress.com/409/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/richnewman.wordpress.com/409/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/richnewman.wordpress.com/409/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/richnewman.wordpress.com/409/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/richnewman.wordpress.com/409/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/richnewman.wordpress.com/409/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/richnewman.wordpress.com/409/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/richnewman.wordpress.com/409/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/richnewman.wordpress.com/409/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/richnewman.wordpress.com/409/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/richnewman.wordpress.com/409/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/richnewman.wordpress.com/409/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/richnewman.wordpress.com/409/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/richnewman.wordpress.com/409/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=richnewman.wordpress.com&amp;blog=909413&amp;post=409&amp;subd=richnewman&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://richnewman.wordpress.com/2010/05/22/a-comparison-of-some-dependency-injection-frameworks-part-5-guice-java/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/20ffeb59bba855d0069ee936add87d8b?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Rich</media:title>
		</media:content>
	</item>
		<item>
		<title>Table of Contents: A Comparison of Some Dependency Injection Frameworks</title>
		<link>http://richnewman.wordpress.com/2010/05/15/table-of-contents-a-comparison-of-some-dependency-injection-frameworks/</link>
		<comments>http://richnewman.wordpress.com/2010/05/15/table-of-contents-a-comparison-of-some-dependency-injection-frameworks/#comments</comments>
		<pubDate>Sat, 15 May 2010 21:09:13 +0000</pubDate>
		<dc:creator>richnewman</dc:creator>
				<category><![CDATA[.net]]></category>
		<category><![CDATA[comparison]]></category>
		<category><![CDATA[Dependency Injection]]></category>
		<category><![CDATA[DI Frameworks]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[dependency injection]]></category>
		<category><![CDATA[dependency injection frameworks]]></category>

		<guid isPermaLink="false">http://richnewman.wordpress.com/?p=396</guid>
		<description><![CDATA[Part 1 Introduction and Motivation A discussion of the motivation behind looking at a number of dependency injection frameworks, and which ones we will look at. Part 2 Scenarios To Be Tested A description of the various tests to be run on the dependency injection frameworks. Part 3 Spring with XML Configuration (Java) A detailed look at running the tests [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=richnewman.wordpress.com&amp;blog=909413&amp;post=396&amp;subd=richnewman&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><a href="http://richnewman.wordpress.com/2010/04/29/a-comparison-of-some-dependency-injection-frameworks-part-1-introduction-and-motivation/">Part 1 Introduction and Motivation</a></p>
<p>A discussion of the motivation behind looking at a number of dependency injection frameworks, and which ones we will look at.</p>
<p><a href="http://richnewman.wordpress.com/2010/05/01/a-comparison-of-some-dependency-injection-frameworks-part-2-scenarios-to-be-tested/">Part 2 Scenarios To Be Tested</a></p>
<p>A description of the various tests to be run on the dependency injection frameworks.</p>
<p><a href="http://richnewman.wordpress.com/2010/05/10/a-comparison-of-some-dependency-injection-frameworks-part-3-spring-with-xml-configuration-java/">Part 3 Spring with XML Configuration (Java)</a></p>
<p>A detailed look at running the tests in Java Spring using XML configuration, with some discussion on the merits of this framework.</p>
<p><a href="http://richnewman.wordpress.com/2010/05/15/a-comparison-of-some-dependency-injection-frameworks-part-4-spring-net-with-xml-configuration-net/">Part 4 Spring.Net with XML Configuration (.Net)</a></p>
<p>A very brief look at running the tests in Spring.Net, which is almost identical to running the tests in Spring for Java with XML configuration.</p>
<p><a href="http://richnewman.wordpress.com/2010/05/22/a-comparison-of-some-dependency-injection-frameworks-part-5-guice-java/">Part 5 Guice (Java)</a></p>
<p>A brief discussion of how Guice works, and a look at the first three tests implemented in Guice.</p>
<p><a href="http://richnewman.wordpress.com/2010/05/22/a-comparison-of-some-dependency-injection-frameworks-part-6-guice-java-continued/">Part 6 Guice (Java) Continued</a></p>
<p>A look at the remainder of the tests implemented in Guice, and some comments on whether the framework solves the problems with other dependency injection frameworks.</p>
<p><a href="http://richnewman.wordpress.com/2010/05/28/a-comparison-of-some-dependency-injection-frameworks-part-7-spring-javaconfig/">Part 7 Spring JavaConfig (Java)</a></p>
<p>Examines how we would run our tests using Spring JavaConfig, and discusses why it seems a step forward from the usual XML configuration in Spring and other frameworks.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/richnewman.wordpress.com/396/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/richnewman.wordpress.com/396/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/richnewman.wordpress.com/396/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/richnewman.wordpress.com/396/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/richnewman.wordpress.com/396/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/richnewman.wordpress.com/396/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/richnewman.wordpress.com/396/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/richnewman.wordpress.com/396/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/richnewman.wordpress.com/396/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/richnewman.wordpress.com/396/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/richnewman.wordpress.com/396/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/richnewman.wordpress.com/396/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/richnewman.wordpress.com/396/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/richnewman.wordpress.com/396/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=richnewman.wordpress.com&amp;blog=909413&amp;post=396&amp;subd=richnewman&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://richnewman.wordpress.com/2010/05/15/table-of-contents-a-comparison-of-some-dependency-injection-frameworks/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/20ffeb59bba855d0069ee936add87d8b?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Rich</media:title>
		</media:content>
	</item>
	</channel>
</rss>
