Images in this post missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at imagehelp@codebetter.com
Castle Windsor - One Small Step Towards Better Software

Update: This is a repost from my old blog, it seemed to have relevance to the recent TypeMock post. It was written for a previous client to help them understand why I was fighting to get Castle Windsor used in their code base.

The Problem

We currently develop software in a fairly piecemeal and disjointed fashion. The software we develop could also be fairly accurately described as monolithic.

There are many problems that come with monolithic code, it becomes hard to maintain, hard to evolve, hard to reuse, and hard to adapt to changing requirements.

Symptoms of a Rotting Design [1] include:

Rigidity

Rigidity is the tendency for software to be difficult to change, even in simple ways. Every change causes a cascade of subsequent changes in dependent modules.

Fragility

Closely related to rigidity is fragility. Fragility is the tendency of the software to break in many places every time it is changed. Often the breakage occurs in areas that have no conceptual relationship with the area that was changed.

Immobility

Immobility is the inability to reuse software from other projects or from parts of the same project. It often happens that one engineer will discover that he needs a module that is similar to one that another engineer wrote. However, it also often happens that the module in question has too much baggage that it depends upon.

Viscosity

Viscosity comes in two forms: viscosity of the design, and viscosity of the environment. When faced with a change, engineers usually find more than one way to make the change. Some of the ways preserve the design, others do not (i.e. they are hacks.) When the design preserving methods are harder to employ than the hacks, then the viscosity of the design is high. It is easy to do the wrong thing, but hard to do the right thing.

What kinds of changes cause designs to rot?

Changes that introduce new and unplanned for dependencies cause rotting designs. Each of the four symptoms mentioned above is either directly, or indirectly caused by improper dependencies between the modules of the software. It is the dependency architecture that is degrading, and with it the ability of the software to be maintained.

In order to forestall the degradation of the dependency architecture, the dependencies between modules in an application must be managed. This management consists of the creation of dependency firewalls. Across such firewalls, dependencies do not propagate.

Object Oriented Design is replete with principles and techniques for building such firewalls, and for managing module dependencies.

The goal

To avoid some of the problems we are currently encountering, we need to move towards software development based on good principles and practices. There is fundamentally little new in software development each year, but better refinement of common patterns and practices, and we should be leveraging those to provide a more stable and adaptable software codebase.

The approach

This document deals with a limited subset of the problem; specifically it is designed to explain the requirements for Castle Windsor and Castle DynamicProxy to be included in our code. As such it does touch on a number of principles that are only partially resolved by the Castle stack, it also omits many other good principles of software development – these can be left for another discussion.

There are a number of aspects of what we currently do that could be improved by better training, better practice, and better communication – but these will not be covered in detail here.

The objectives

So as our problem is relatively wide in scope, here are some specific principles that we should be aiming for in our code. These are fairly widely established principles within the industry, so none should be of any great surprise. Possibly the greater surprise will be that we are using almost none of these, at least not in any explicit or agreed upon method. This list is only a subset of a wider set or principles we should be aiming for.

Single Responsibility Principle (SRP) [2]

There Should Never Be More That One Reason for a Class to Change

Responsibilities should be considered as axis of change – if a class assumes more than one responsibility, then it has more than one possible reason to change, and becomes a weak point in the design. This coupling leads to fragile designs that break in unexpected ways.

This class level principle applies at a wider level, where it is commonly referred to as Separation of Concerns.

Separation of Concerns (SoC) [3]

The principle that software components should be broken to smaller parts that overlap in functionality as little as possible. Examples of SoC in practice would be adoption of design patterns such as Model-View-Presenter, or Service Oriented Architecture.

A concern at modular level could be considered the separation of display logic, from business logic. The separation of data access from data manipulation. Or at a lower level, the separation of configuration from processing logic.

By separating each of the concerns away from each other – you obtain the ability to alter each of those concerns independently, whether due to a change in the requirements, and evolution of the system, a bug fix, or for any other reason you may have for change.

Application of SoC allows you to create and evolve Loosely Coupled Systems, a primary objective of good software design.

The Dependency Injection Principle (DIP) [4]

A: High Level Modules Should Not Depend Upon Low Level Modules, Both Should Depend Upon Abstractions
B: Abstractions Should Not Depend Upon Details, Details Should Depend Upon Abstractions

By inverting the dependency structure we eliminate a common problem where a small change to environment or requirements cascades through our entire application. By using the DIP we isolate those changes.

Consider the most commonly written example, that of a class or component that requires configuration information – for the sake of this example let us refer to it as the DataService class.

A traditional approach to writing this might be to have the DataService class call the ConfigurationManager to get the settings it requires. At this point however, your class now depends upon the ConfigurationManager – it cannot be compiled if this manager is not present, it cannot execute if this class is not present, and it cannot have the source of its configuration information changed without a recompilation at least, and possibly a rewrite at worst.

Dependency Injection turns this concept upside down – quite literally. This is why this is commonly referred to as Inversion of Control (IoC) [5]

We now design our DataService class so that instead of it talking directly to a ConfigurationManager, it is given an abstraction of the ConfigurationManager by the code that created our class. The responsibility for the source and creation of the ConfigurationManager is no longer a concern of our DataService class, but of the thing that created it. So in our example we create an interface called IConfigurationManager, one implementation of which is our real ConfigurationManager. Now when we create our DataService, we tell it specifically which instance of IConfigurationManager it should use to get its configuration information.

This principle has multiple benefits, apart from helping achieve the primary objectives of maintainability, SoC and SRP, it also fulfils one other fundamental objective, it allows Unit Testing.

If a class like our original DataService is to be unit tested, we must have a ConfigurationManager in place. The ConfigurationManager must be the exact same version as will be used in our application, and it will bring with it all the dependencies it contains. In fact, you will probably have to put the DataService into a nearly fully implemented application, just to test a basic part of its behaviour.

After we have applied Inversion of Control we can now unit test the DataService independently of its configuration requirements. We can create a mock implementation of our IConfigurationManager that passes in a known configuration set, and therefore allows us to have a known outcome state after a request. We are no longer tied to tests that may break when someone changes the format of the configuration data, or changes the data store, and in the case of our DataService, we no longer require a database in place, just to see if the DataService correctly requests database information.

Unit Testing and Test Driven Development [6][7]

By using Inversion of Control we can now write valid unit tests. The qualification of “valid” is very important here, a poor unit test is one that tests more than it should – in much the same way as application of SRP, a unit test that tests more than one thing is fragile and prone to breaking for the wrong reasons.

A differentiation should also be drawn between a “unit test” and an “automated integration test”. While both may use a xUnit framework such as NUnit or MbUnit, there is a very important distinction. A unit test tests one thing and one thing only ... it tests a “unit” – an integration test tests more than one thing, hence it is not a unit test.

So back to our previous example, a unit test that tested a function of the DataService is desirable and should be our primary objective, but if it was to test the DataService that called the ConfigurationManager, it is now actually testing at least two components, and is possibly testing a few dozen more (all of the dependencies that ConfigurationManager has are being tested too). With IoC we can provide a mock IConfigurationManager and ensure we are only testing the DataService – a single unit. Changes to the ConfigurationManager implementation or one of its dependencies can no longer break our unit tests.

Not only that, but it is entirely possible in our example that we cannot unit test our DataService at all, as it requires infrastructure code and data that may not be present at test time. It is also highly likely that we will end up with a large and interdependent set of configuration sources within our tests to try and mimic all the possible permutations of configuration data we may expect, creating highly fragile and hard to understand tests.

One simple abstraction avoids all of this.

The solution

So Why Do We Need an Inversion of Control Container?

The example given so far is pretty easy to follow. We don’t access configuration within our DataService, but the code that creates the DataService also creates the ConfigurationManager implementation and passes it in.

However if you follow this all the way down the software stack, you will realise that at some point, there must be a concrete dependency ... something has to know how to create all these concrete dependencies, and therefore it has the dependencies itself.

This is where an IoC container such as Castle Windsor comes into play.

What Does Castle Windsor [8] Do?

Inversion of Control containers allow you to achieve loosely coupled designs and they handle dependency and configuration management when you, or a class in your system, request a service to say, send e-mails, you will get an instance ready to be used.

IoC containers favour reuse as they allow you to use a natural idiom to expose the component's dependencies. This allows components to be used with or without containers. Hence you quickly end up with a library of reusable components that can be shared among projects, as long as you apply the Separation of Concerns principle.

Castle Windsor allows components within the system to be registered with it, and when it receives requests for those objects, it is responsible for creating them, and maintaining their lifestyles. Where you require a singleton, it will provide that for you, and where you require a thread pooled object, it can provide that for you too – without any alteration of your codebase.

More importantly, it is capable of resolving all sub-dependencies that a class has. So back to our example, we don’t need to create an instance of the IConfigurationManager, and an instance of the DataService, or create any instances of all the other things that DataService may depend upon – Windsor knows all of this and will do this work for us.

So when we ask Windsor to give us the DataService, it will create all dependency objects too, pull configuration from an external source if we have specified that, and return us back a single fully constructed object graph. This avoids the problems of fragile code, as a change to the dependencies of our DataService is now transparent to all the code that uses our DataService.

Windsor also brings additional benefits far beyond the basics of object creation and management. As it contains the ability to create interceptors, it becomes very easy to add functionality that exposes cross cutting concerns such as logging. When we request our DataService now, Windsor knows that our configuration says Windsor should attach a logger to our methods, and it will do all the work needed to create the classes to manage those objects. This functionality can be extended to allow for many other cross cutting concerns such as authentication, authorization, and extension of existing business logic.

The critical part of Windsor for us in many respects is that it is highly extensible; almost any scenario you can envisage with regards to object creation or management is a simple step to configure or to extend.

What is Castle Windsor?

Castle Windsor is a component part of the Castle open source project that has been in existence since 2003, and was built upon lessons learned from the Java community and earlier .Net projects.

Most recently, part of the Castle stack, MonoRail has been a major factor in Microsoft moving towards MVC development under ASP.NET, with contributors to MonoRail being asked for their views on the development direction by the team developing ASP.NET MVC

Castle Windsor could also be said to have been a major influence in Microsoft creating their own Inversion of Control container, Unity. Unity is currently only under CTP, but will be released, as Castle Windsor is, with an open licence and source code available. There are a number of differences between Windsor and Unity, this document does not discuss them, and instead recommends Windsor initially, with an option to move to Unity should that need become apparent or viable in future – at present Unity does not solve many of the scenarios we wish to cover.

Licensing for Castle Windsor

It is released under the terms of Apache Software Foundation License 2.0 [9], which is possibly the most open of all licences. The Apache License (versions 1.0, 1.1, and 2.0) requires preservation of the copyright notice and disclaimer, but it is not a copyleft license — it allows use of the source code for the development of free and open source software as well as proprietary software. Although lawyers can give you a legal list of restrictions this imposes, it fundamentally comes down to “do what you want with it as long as the copyright notice remains”

What is the Support Behind Castle Windsor?

As an open source project, Castle Windsor could be said to be one of the most mature and continually developed projects around. Although officially at RC3 for a large number of months so far, this is mainly due to a project requirement that version 1.0 will not be released until the external API can be guaranteed to be stable.

On a daily basis, Castle Windsor can be considered highly stable, and is being constantly developed. The few bugs that are present are resolved rapidly, and there is commercial support available should that be a requirement – though with full access to the source code this would appear unnecessary.

[1] Robert C Martin :
http://www.objectmentor.com/resources/articles/Principles_and_Patterns.pdf
[2] Robert C martin :
http://www.objectmentor.com/resources/articles/srp.pdf
[3] Wikipedia :
http://en.wikipedia.org/wiki/Separation_of_concerns
[4] Robert C Martin :
http://www.objectmentor.com/resources/articles/dip.pdf
[5] Wikipedia :
http://en.wikipedia.org/wiki/Inversion_of_control
[6] Wikipedia :
http://en.wikipedia.org/wiki/Unit_testing
[7] Wikipedia :
http://en.wikipedia.org/wiki/Test-driven_development
[8] Castle :
http://www.castleproject.org/container/gettingstarted/index.html
[9] Wikipedia :
http://en.wikipedia.org/wiki/Apache_license


Posted 05-02-2008 7:18 AM by Jak Charlton

[Advertisement]

Comments

Paul Kinlan’s Development Blog » Development Link Goodness 4th May 2008 wrote Paul Kinlan’s Development Blog » Development Link Goodness 4th May 2008
on 05-04-2008 8:40 AM

Pingback from  Paul Kinlan’s Development Blog » Development Link Goodness 4th May 2008

Reflective Perspective - Chris Alcock » The Morning Brew #87 wrote Reflective Perspective - Chris Alcock » The Morning Brew #87
on 05-06-2008 3:23 AM

Pingback from  Reflective Perspective - Chris Alcock  » The Morning Brew #87

Casey Charlton - Insane World wrote The Only Certainty is Change
on 05-14-2008 2:52 AM

I got an email at the end of last week asking about Agile development in the enterprise, and I guess

InsaneWorld wrote The Only Certainty is Change
on 10-26-2008 5:34 PM

The Only Certainty is Change

About The CodeBetter.Com Blog Network
CodeBetter.Com FAQ

Our Mission

Advertisers should contact Brendan

Subscribe
Google Reader or Homepage

del.icio.us CodeBetter.com Latest Items
Add to My Yahoo!
Subscribe with Bloglines
Subscribe in NewsGator Online
Subscribe with myFeedster
Add to My AOL
Furl CodeBetter.com Latest Items
Subscribe in Rojo

Member Projects
DimeCasts.Net - Derik Whittaker

Friends of Devlicio.us
Red-Gate Tools For SQL and .NET

NDepend

SlickEdit
 
SmartInspect .NET Logging
NGEDIT: ViEmu and Codekana
LiteAccounting.Com
DevExpress
Fixx
NHibernate Profiler
Unfuddle
Balsamiq Mockups
Scrumy
JetBrains - ReSharper
Umbraco
NServiceBus
RavenDb
Web Sequence Diagrams
Ducksboard<-- NEW Friend!

 



Site Copyright © 2007 CodeBetter.Com
Content Copyright Individual Bloggers

 

Community Server (Commercial Edition)