Mark Needham

Thoughts on Software Development

Archive for March, 2009

Re-reading books

with 7 comments

An interesting thing that I’ve started to notice recently with regards to software development books is that I get a lot more from reading the book the second time compared to what I did reading the book the first time.

I’ve noticed this for several books, including The Pragmatic Programmer, Code Complete and Domain Driven Design, so my first thought was that perhaps I had read this books too early when I didn’t have the necessary context or experience to gain value from reading them.

A conversation with Ade led me to believe that perhaps this isn’t the case and in actual fact reading the book the first time pushes your thinking in certain directions even though you don’t necessarily realise it.

Coming back to the same book again seems like it should be a waste of time, but I think we have different ideas about what is important when it comes to developing software and therefore the book affects us in different ways despite the fact that the content is exactly the same.

With the three books I mentioned above, the first time I read each of them the advice seemed fairly obvious and continuing with this attitude I struggled to get much out of them.

The Pragmatic Programmer was the first one I re-read and the second time I read it I was getting into the idea of automation around build and deployment so the parts of the book which talk about automation really stood out for me. A lot of other places where automation would be useful became apparent to me from reading the book the second time.

I started re-reading Code Complete after a recommendation from Dave but this time my focus was heavily on the expressibility of our code as this is the area of coding that I am very interested in at the moment. Some of the ideas around variable naming are superb and are directly linked to some of the mistakes I have made recently in this area. It was very interesting for me to see this in a book I hadn’t picked up for a few years.

Domain Driven Design is by far the most recommended book amongst developers at ThoughtWorks and I am currently reading it for the second time but this time as part of a technical book club. I have learnt how the specification pattern can be applied on real projects thanks to examples show to me by Alex but in particular the idea of bounded contexts has started to make way more sense to me due to the fact that we didn’t follow this idea on a recent project and really suffered as a consequence.

I’m sure when I read these books again I will learn something else that I didn’t learn the first or second times.

More than just books…

I think this can also apply to the way that we learn other things such as different styles of programming.

For example, I studied functional programming at university but I never really saw the benefits that we could get from it – the lecturer just pointed out that it was ‘better’ than using an imperative language which didn’t really resonate with me.

Having played around with Erlang and F# a bit and seeing some of the problems we cause ourselves in non functional languages by having mutable state I am starting to understand and like it much more.

The realisation for me has been that we don’t have to understand or get everything the first time we do it, there are plenty more opportunities to do that.

And on a book specific level, to make sure I read books more than once to see what I get out of them the next time!

Written by Mark Needham

March 19th, 2009 at 10:49 am

Coding: Make it obvious

with 9 comments

One of the lessons that I’ve learned the more projects I work on is that the most important thing to do when coding is to do so in a way that you make life easier for the next person who has to come across that code, be it yourself or one of your team mates.

I think the underlying idea is that we need to make things as obvious as possible.

Obvious naming

This one seems like it should be so easy and yet it’s incredibly easy to get it wrong.

In a presentation I watched by Dan Bergh-Johnsson last week he talked about the need to name methods and classes in an obvious way because when a developer wants to implement some functionality they will spend a maximum of 30 seconds seeing whether it’s been done before and if they don’t find anything they’ll do it themself.

I recently started reading through Code Complete again having left it on the shelf for the last 3 years and there are some excellent ideas in the book about the best way to name things in our code.

Describing variables in terms of the problem domain instead of in terms of the technical solution i.e. describing the what not the how is one of the best pieces of advice from the chapter on variable naming.

Beyond that we need to know what the purpose of a variable is in a given context otherwise it can be very easy to choose a name that will make no sense to someone later on.

For example I recently named a variable ‘DefaultCustomerDetails’ to indicate that if that variable was set then that meant the customer details should be defaulted and not be editable. I thought it made sense but when a colleague read it they had no idea what I meant by it – what we actually wanted to say was ‘AreCustomerDetailsEditable’ which is what I should have named it! The purpose on this occasion was to indicate whether to show a read only or editable version of the customer details section of the page.

Obvious use of patterns

This is one that was only recently pointed out to me by Dave when discussing the way I had implemented the builder pattern in our code base.

I was trying to remove the need to call a ‘Build’ method by making use of C#’s implicit method which I thought was a good idea to remove noise from the code, but as Dave pointed out wasn’t what other people would expect when they came across the use of the pattern and therefore created confusion.

I’m not sure whether this means that we should name all of the patterns we use in code but I think at least we should use them in a consistent way and pick the most obvious pattern for the job rather than choosing a solution that may be clever but less clear to other people.

Patterns are useful for helping to make our code more expressive and if we keep this idea in mind then I think it will guide us down the right path and not create a level of indirection in vain.

Obvious examples of API use

In terms of obviousness our test code is just as important as our production code.

Tests shouldn’t have clutter in them and they should have just enough context needed to understand how the different objects in our system interact and the APIs available for each of them.

Making use of the builder or object mother to avoid polluting our tests with too much data, following a consistent pattern such as ‘Act-Arrange-Assert’ in the tests so people can quickly work out what’s going on as well as naming tests accurately all help in this aspect.

In Summary

These are the main three areas where I’ve found being obvious can have the most benefit.

I’m sure there are others that I haven’t thought of so feel free to let me know your favourite ways of writing code that others on your team can use with ease.

Written by Mark Needham

March 18th, 2009 at 10:44 am

Posted in Coding

Tagged with

QCon London 2009: The Power of Value – Power Use of Value Objects in Domain Driven Design – Dan Bergh Johnsson

with 6 comments

The final Domain Driven Design talk I attended at QCon was by Dan Bergh Johnsson about the importance of value objects in our code.

I thought this session fitted in really well as a couple of the previous speakers had spoken of the under utilisation of value objects.

The slides for the presentation are here.

What did I learn?

  • Dan started the talk by outlining the goal for the presentation which was to ‘show how power use of value objects can radically change design and code, hopefully for the better’. A lot of the presentation was spent refactoring code written without value objects into shape.
  • We started out with a brief description of what value objects are not which I found quite amusing. To summarise,they are not DTOS, not Java beans and not objects with public fields. The aim with value objects is to swallow computational complexity from our entities. Creating what Dan termed ‘compound value objects’ provides a way to do this. The benefits of doing this are reduced complexity in entities and code which is more extensible, more testable and has less concurrency issues.
  • I found myself quite intrigued as to how you would be able to spot an opportunity in your code to introduce a value object and almost as soon as I wrote down the question Dan covered it! Some opportunities include strings with format limitations, integers with limitations or arguments/results in service methods. The example used was a phone number which was being passed all over the place as a string – refactoring this allowed the code to become explicit – before the concept existed but it was never properly spelled out – and it pulled all the functionality into one place.
  • Dan’s term for this was ‘data as centres of gravity‘ – once you have the value object anything related to that data will be drawn towards the object until you have a very useful reusable component. He pointed out that ‘your API has 10-30 seconds to direct a programmer to the right spot before they implement it [the functionality] themselves‘. I think this was a fantastic reason for encouraging us to name these objects well as we pretty much only have the amount of time it takes to hit ‘Ctrl-N’ in IntelliJ, for example, and to type in a potential class name.
  • Another interesting point which was being discussed on twitter as the presentation was going on was whether we should be going to our domain expert after discovering these value objects and asking them whether these objects made sense to them. Dan said that this is indeed the best way to go about it. I have to say that what struck me the most across all the presentations was the massive emphasis on getting the domain expert involved all the time.
  • Seemingly randomly Dan pointed out an approach called composite oriented programming which is all about using DDD terminology but inside a framework to drive development. I’ve only had a brief look at the website so I’m not sure if it’s anything worth shouting about.
  • In the second half of the session compound value objects were introduced – these basically encapsulate other value objects to come up with even more explicitly named objects. The examples in the slides are very useful for understanding the ideas here so I’d recommend having a look from slide 44 onwards. The underlying idea is to encapsulate multi object behaviour and context and make implicit context explicit. This idea is certainly one that is new to me so I’m going to be looking at our code base to see if there’s an opportunity to introduce the ideas I learnt in this talk.
  • To close Dan rounded up the benefits we get from introducing value objects into our code – context aware client code, smart services and a library with an API.

Written by Mark Needham

March 15th, 2009 at 9:45 am

Posted in QCon

Tagged with , ,

QCon London 2009: Rebuilding guardian.co.uk with DDD – Phil Wills

with 5 comments

Talk #3 on the Domain Driven Design track at QCon was by Phil Wills about how the Guardian rebuilt their website using Domain Driven Design.

I’d heard a little bit about this beforehand from colleagues who had the chance to work on that project but it seemed like a good opportunity to hear a practical example and the lessons learned along the way.

There are no slides available for this one on the QCon website at the moment.

What did I learn?

  • Phil started by explaining the reasons that they decided to rebuild their website – tedious manual work was required to keep the site up to date, they were struggling to hire new developers due to their choice of technology stack and it was difficult to implement new features.
  • They were able to get domain experts very involved with the team to help define the domain model and trusted the domain expert to know best. I think the difficulty of making this happen is underestimated – none of the projects that I’ve worked on have had the domain expert access that Phil described his team as having. The benefit of having this was that they had times when the business pointed out when the model was getting over complicated. The takeaway comment for me was that we should ‘strive to a point where the business can see and comprehend what you’re trying to achieve with your software
  • Entities are your stars but we need to also think about value objects. Entities have the maintenance overhead of having life cycle that we need to take care of so it makes sense to avoid this wherever possible. Phil showed an example of an entity class with around 50 fields in which could have been severely simplified by introducing value objects. Every time I heard value objects being mentioned it reminded me of micro/tiny types which are not exactly the same but seem to be fairly similar in their intent of improving expressiveness and making the code easier to work with. The importance of value objects was also mentioned in Eric Evans talk.
  • The database is not the model – Phil repeated this multiple times just in case we didn’t get the picture, and it was something Dan mentioned in his talk as well where he referenced Rails use of Active Record as being a particular culprit. Phil mentioned that this had been a difficult idea to grasp for some of the team who didn’t give full status to data that didn’t have a corresponding place in the database.
  • The Guardian’s core domain is articles – they look to use 3rd party solutions for parts of the website which aren’t part of the core domain. For example football league tables are pulled from a 3rd party content provided who sends the data in a format which can be easily displayed on the website. I think I would have made a mistake here and tried to model the league table so it was cool that they recognised that there wasn’t going to be much value in doing this since it’s not their differentiator. This was a really useful example for helping me to understand what the core domain actually is.
  • Although the database is not the model, Phil pointed out that keeping the database near to the model helps save the need to do lots of context switching. Interestingly he also pointed out that it’s not always good to completely normalise data – it can lead to expensive joins later on.
  • One idea which I felt wasn’t completely explained was that of injecting repositories into domain model objects to get access to some data rather than having to do a traversal by accessing it through other means. Phil said this was considered a bit of a hack but was sometimes a good choice. He did also point out that it can hide problems with the model.
  • Future plans for the code include adding domain events and trying to create a less monolithic domain – there is currently a single shared context which makes it difficult to prise stuff that’s not in the core domain away.

Written by Mark Needham

March 14th, 2009 at 2:23 pm

Posted in QCon

Tagged with , ,

QCon London 2009: DDD & BDD – Dan North

with 2 comments

The second presentation in the Domain Driven Design track at QCon was titled ‘DDD & BDD‘ and was presented by my colleague Dan North – a late stand in for Greg Young who apparently injured himself playing ice hockey.

Eric did an interview with Greg at QCon San Francisco 2007 where Greg talks about some of his ideas and apparently there is an InfoQ video kicking around of Greg’s ‘Unshackle Your Domain’ talk from QCon San Francisco 2008 which we were told to pester InfoQ to post on their website!

Anyway this one was Dan’s talk about the relation between Domain Driven Design and Behaviour Driven Development.

The slides for the presentation are here.

What did I learn?

  • Dan briefly covered some of the Domain Driven Design basics, including quoting Jimmy Nilsson on what it actually is:

    Focus on the domain and letting it affect the software very much

    A fairly succinct way of summing up the book in one sentence I think!

  • Dan described the core domain as being your differentiator (what makes you special), the thing the stakeholders care most about, the place where the most interesting conversations are going to be, the richest seams for knowledge crunching. I don’t think I really understood what the core domain was before watching this presentation – it also helped me make sense of Eric Evans’ comment in the previous talk where he spoke of not spreading the modeling too thin, instead keep it focused on the areas that provide you most value.
  • He spoke of the benefits of having a shared language used by everyone on your team – you don’t have the translation effort which is very tiring! Driving the language into everything has the added benefit of giving you a place to put behaviour, otherwise it ends up spread all over the place. Dan spoke of the ubiquitous language only being consistent within a bounded context – not really so ubiquitous after all!
  • Next up was the other side of the coin – Behaviour Driven Development. He described BDD as ‘focusing on the behaviour of an application from the point of view of its stakeholders‘, where the stakeholders are anyone who cares about the application. BDD is about outside-in development where requirements are expressed as stories which have acceptance criteria to help us know when we’re ‘done’. The acceptance criteria are comprised of scenarios made up of steps and these then become acceptance tests when they are completed. He also riffed a bit about bug driven development – outside in taken to the extreme.

    Dan made an interesting point that BDD is about a mindset rather than the tools and I think I agree there – I’ve not used the tools much but I try to consider the behaviour I’m trying to drive whenever I’m writing tests/examples.

  • For a while I’ve preferred to describe the way I write code as being driven by example rather than driven by tests but it is still referred to as TDD – Dan helped me to see how this makes sense. We code by example to implement features but when those examples are done then they act as tests.
  • Dan spoke of the ‘Glaze Effect‘ when speaking with domain experts i.e. when you talk using language from a domain they don’t understand – probably using language that is too technical for them to care.
  • Dan said the first part of the book is effectively ‘The Hobbit’ but the really interesting stuff only comes in ‘The Lord of the Rings’ which is the second part. That’s pretty much my experience as well – I gained way more from reading the second half than the first half. Dan pointed out that the ideas around scaling DDD are applicable anywhere – they’re not specific just to DDD.
  • BDD is about conversations in the ubiquitous language to produce software while DDD is about exploring the domain models that stakeholders use. Discovering these domain models can be valuable even if you don’t end up writing any code.
  • There is a circular dependency between BDD and DDD – we can’t have behaviour driven conversations without DDD and BDD helps structure the conversations you can have in DDD. The structure that the Given, When, Then scenarios provide for having conversations was also identified as being a key part of how BDD can be useful. When it comes to coding, DDD helps drive the design and BDD helps drive what you develop.

Written by Mark Needham

March 14th, 2009 at 1:28 am

Posted in QCon

Tagged with , ,

QCon London 2009: What I’ve learned about DDD since the book – Eric Evans

with 9 comments

I went to the QCon conference in London on Thursday, spending the majority of the day on Eric Evans’ Domain Driven Design track.

The opening presentation was by Eric Evans, himself, and was titled ‘What I’ve learned about DDD since the book‘.

In the 5 years since the book was published, I’ve practiced DDD on various client projects, and I’ve continued to learn about what works, what doesn’t work, and how to conceptualize and describe it all. Also, I’ve gained perspective and learned a great deal from the increasing number of expert practitioners of DDD who have emerged.

We’re currently reading Domain Driven Design in our technical book club in the ThoughtWorks Sydney office so I was intrigued to hear about Eric’s experiences with DDD and how those compared with ours.

The slides from the presentation are here.

What did I learn?

  • We started with a look at what Evans considers the most essential parts of DDD – creative collaboration between the software experts and the domain experts was identified as being important if we are to end up with a good model. If we can make the process of defining the model fun then all the better but we need to utilise domain experts properly and not bore them.

    Taking a domain expert through some screens and talking about the validation needed on different fields is a bad way to use them – they want to do valuable work and if this is their experience of what it’s like working with the software experts then we’ll never see them again.

  • When we’re modeling we need to come up with at least three models – don’t stop at the first model, it’s probably not going to be the best one. If we stop after one model then we’re leaving opportunities on the table – white boarding different models is a very cheap activity so we should make sure we take advantage of that and do it more frequently.

    When we talk of three models Evans’ pointed out that these should be different to each other and that this would involved coming up with some radically different ideas. Creating an environment where we can celebrate ‘bad’ ideas is necessary to encourage people to step into the riskier territory. If we’re only coming up with good ideas we’re not being creative. This was a definite take away for me – I’m certainly guilty of only considering the first model I discover so this is something to improve on.

  • He touched on a couple of others including the need to constantly reshape the domain model as we learn more about it and that we can get the biggest gain from DDD by keeping the focus on our core domain before we got onto explicit context boundaries – I’ve always found this to be the most interesting part of the book and Evans said he wished he’d made it one of the earlier chapters.

    I spoke with him afterwards about whether or not the UI was considered to be a separate bounded context. He said to consider a bounded context as an observation [of the system] and that if the model of the UI was significantly different to the underlying model then it would be reasonable to consider it as another bounded context.

  • We moved onto the building blocks of DDD – services, entities, value, objects, factories, repositories – which Evans considers to be over emphasised. They are important but not essential. Evans did also point out that value objects tend to get neglected. This was also mentioned in several of the other presentations.
  • Despite this Evans added a new building block – domain events. He described this as ‘something happened that the domain experts care about’. They provide a way of representing the state of an entity and lead to clearer, more expressive model. This sounded very similar to an approach Nick has described to me whereby we would have a new object that represented a specific state of an object. ‘Every change to an object is a new object’ was the take away quote from this part of the talk for me – I think an explicit approach to modeling is far superior to an implicit one.

    The example given was a baseball game where a domain event might be someone swinging at the ball – when this happens statisticians will need to be informed so that they can update their statistics i.e. we often want to record to events that happen in our domain. He described the use of an event stream which we could put events onto and they could be subscribed to by whoever cares e.g. the reporting service.

  • Evans made an interesting point when talking about strategic design – just because you have been working in a domain for a long period of time does not make you a domain expert. There is a subtle difference between someone working as a software expert in a domain and the actual domain expert – when looking at problems the software expert is responsible for looking at how software can help, the domain expert is responsible for removing that problem!
  • Evans came up with a context mapping step-by-step which he said could be followed to help us work out where the different bounded contexts in our system are and how they interacted:
    1. What models do we know of? (draw blob for each & name it)
    2. Where does each apply?
    3. Where is information exchanged?
    4. What is the relationship?
    5. Rinse and repeat

    I’ve never drawn a context map before but it sounds like a potentially valuable exercise – might try and do one for my current project!

  • He also added a couple more patterns in this area – big ball of mud and partners. For big ball of mud he said we should identify these in our context maps and then not worry too much about applying design techniques when in this context – just take a pragmatic approach and ‘reach in and change it’

    Partners was described as being similar to a three-legged race – both teams need to cooperate on their modeling efforts because they have a mutual dependency, neither can deliver without the other.

  • Some final take away quotes included ‘not all of a large system will be well designed‘ and ‘precision designs are fragile‘ – where we have the latter in our code we need to protect them with an anti corruption layer and with the former we should pick a specific area (that matters) to design well and accept that other bits might not be as good as this bit.

Gojko Adzic has a write up of this talk as well – a very informative talk and it’s definitely cool to hear the guy who coined the approach talking about it.

Written by Mark Needham

March 13th, 2009 at 8:56 pm

Posted in QCon

Tagged with , ,

OO: Reducing the cost of…lots of stuff!

with 4 comments

I’ve been working in the world of professional software development for a few years now and pretty much take it as a given that the best way to write code which is easy for other people to understand and work with is to write that code in an object oriented way.

Not everyone agrees with this approach of course and I’ve been told on occasions that I’m ‘over object orienting’ (is that even a word?) solutions. However, I think there are big advantages to be had from following an OO approach and I thought I’d explore these here.

Writing code in an object oriented way provides a way for us to manage complexity in an application. There always seems to be some degree of complexity, even in simple looking problems, so it makes sense to look for ways to mitigate that.

I think it’s fair to say that it is easier to write code in a procedural or quasi procedural/object oriented way whereby we tend to use ‘objects’ as data containers which we can shove data into and then take data out to use wherever we need to, and to start with we really don’t see any ill effects from doing this – the application still does what it’s supposed to, our acceptance tests pass and we chalk up our story points.

Then comes the time when we need to make changes to that code, and those times keep coming – a quote from Toby Young’s presentation at QCon London has him suggesting the following:

92% of cost is maintaining/supporting/upgrading existing systems; only 8% on new stuff.

Given that type of data I think it makes sense for us to try and make it as easy as possible to make those changes.

From my experience we tend to get this ‘nightmare to change mix of object oriented and procedural code’ mainly due to violations of the law of demeter i.e. putting getters on our classes and from copious use of setters which leave our objects in an inconsistent state.

We can immediately get a lot of benefits by not doing this – by setting up our objects in their constructors and by telling objects what to do rather than asking for data from them and choosing what to do with that data elsewhere.

So what are these benefits?

Reduced cost of change

One example I came across lately was to do with the creation of models to use on our views – using the ASP.NET MVC framework.

The models were being assembled somewhat similarly to this:

var parentModel = new ParentModel
				  {
					ChildModel = new ChildModel
								 {
									Property1 = new OtherObject(SomeCollection(), parentModel.SomeOtherProperty);
								 }				
				  };

It starts off fairly harmless, using the object initializer syntax, but what if we decide to change Property1 to be say Property2 as happened to us?

If we had set this through the constructor then we would have only had to make the change in one place and then we could have moved on.

In actual fact it turned out that there were 4 places where we were setting Property1 – all of them from within the controller in a similar way to the above example.

After a bit of investigation I realised that only one of those cases was being tested even though the property was being constructed slightly differently in a couple of the places.

As Michael Feathers teaches us in Working Effectively with Legacy Code if we’re going to try and refactor code we need to ensure first of all that there is a test which covers that functionality so that if we mistake we are informed of it.

This took longer than I expected due to the fact that there was quite a bit of setup needed since the only place to test this was through the controller.

If we had followed an object oriented approach here then not only would these tests have been easier to write, but they would have been written in the first place and not got forgotten about in the mess of the controller.

In theory what was a very simple change ended up taking a few hours.

Code that is much easier to test

As I mentioned earlier when we code in an object oriented way it becomes much easier to test because the context that we need to consider in our tests is massively reduced.

In the above example we should be able to test whether of not Property1 was being set correctly directly from the ChildModel rather than having to test it from our controller. Unfortunately by having it set through a setter we can’t do this in a meaningful way.

The creation of ‘OtherObject’ should be done inside the ChildModel and we can pass in the other data into the constructor of the class and then call Property1 in our test to see whether or not we get the expected result. We might end up with a ChildModel that looks more like this:

public class ChildModel
{
	public ChildModel(IEnumerable<string> someCollection, string selectedValue)
	{
		this.someCollection = someCollection;
		this.selectedValue = selectedValue;
	}
 
	public SomeObject Property1
	{
		get 
		{
			return new SomeObject(someCollection, selectedValue);
		}
	}
}

I know the example is contrived but hopefully the idea that putting this type of logic leads to easier to test units of code is clear.

Less need to debug

Another truly annoying consequence of creating train wreck code is that you end up with null pointer/reference exceptions all over the place and it’s quite difficult to immediately tell which part of the train caused the problem.

Since it would take a long time to get that segment of code under test and identify the problem that way out comes the debugger so that we can find out what went wrong.

It might help solve the problem this time but unless we change our coding style to remove this type of problem from happening then it’s just as likely to happen again tomorrow and we’ll be back to square one.

I hate using the debugger – it takes a long time to step through code compared to a TDD cycle and once you’ve solved the problem there isn’t an executable example/test that you can run to ensure that it doesn’t make a reappearance.

If we can write our code in an object oriented fashion then we pretty much remove this problem and our time can be spent much more effectively adding real value to our application.

Written by Mark Needham

March 12th, 2009 at 4:04 am

Posted in OOP

Tagged with ,

OO: Micro Types

with 12 comments

Micro or Tiny types present an approach to coding which seems to divide opinion in my experience, from those who think it’s a brilliant idea to those who believe it’s static typing gone mad.

I fall into the former group.

So what is it?

The idea is fairly simple – all primitives and strings in our code are wrapped by a class, meaning that we never pass primitives around.

In essence Rule #3 of Jeff Bay’s Object Calisthenics.

As I mentioned on a previous post about wrapping dates, I was first introduced to the idea by Darren Hobbs as a way of making APIs easier for others to use.

In the world of Java method signatures of 3rd party libraries with minimal Javadoc documentation tend to read like so when you look at their method signatures in your chosen editor.

doSomething(string, string, string, string)

The parameter name is sometimes not available meaning that it is now almost impossible to work out what each of those strings is supposed to represent – guesswork becomes the way forward!

I noticed an even more subtle example when working on a project last year where there was a method to transfer money between accounts. It looked like a bit like this:

public void transferMoney(Account debitAccount, Account creditAccount) {
	// code
}

See how easy it would be to get those accounts the wrong way around and suddenly the money is going in the wrong direction!

I always had to look twice to make sure we were doing the right thing – it was quite confusing.

Using micro types we could solve this problem by wrapping account with a more specific class. The signature could potentially read like so:

public void transferMoney(DebitAccount debitAccount, CreditAccount creditAccount) {
	// code
}

And the confusion has been removed.

The cost of doing this is obviously that we need to write more code – for the above example maybe something like this:

public class DebitAccount {
	private Account debitAccount;
 
	public DebitAccount(Account debitAccount) {
		this.debitAccount = debitAccount;
	}
}

We’d then delegate the necessary method calls through to the underlying Account although we probably don’t need to expose as many methods as the normal account object would since we only care about it in this specific context.

I had the opportunity to work on a project led by Nick for a couple of months last year where we were micro typing everything and I quite enjoyed it although opinion was again split.

I felt it helped to keep behaviour and the data together and was constantly forcing you to open your mind to new abstractions.

The other argument against the approach is that you are creating objects which have no behaviour.

I find here that it depends what you classify as behaviour – for me if there is some logic around the way that a string is formatted when it is going to be displayed then that is behaviour and we should look to put that logic as close to the data as possible i.e. within the micro type.

On that project each object rendered itself into a ViewData container which we accessed from our views.

public class Micro {
	private string micro;
 
	public Micro(string micro) {
		this.micro = micro;
	}
 
	public void renderTo(ViewData viewData) {
		viewData.add(micro);
	}
}

If an object contained more than one piece of data it could then decide which bits needed to be rendered.

It’s certainly not for everyone but it’s an approach that I felt made coding much more enjoyable and code much easier to navigate.

Written by Mark Needham

March 10th, 2009 at 10:40 pm

Posted in OOP

Tagged with ,

DDD: Repository pattern

with 4 comments

The Repository pattern from Domain Driven Design is one of the cleanest ways I have come across for separating our domain objects from their persistence mechanism.

Until recently every single implementation I had seen of this pattern involved directly using a database as the persistence mechanism with the repository acting as a wrapper around the Object Relational Mapper (Hibernate/NHibernate).

Now I consider there to be two parts to the repository pattern:

  1. The abstraction of the persistence mechanism away from our other code by virtue of the creation of repositories which can be interacted with to save, update and load domain objects.
  2. The need for these repositories to only be available for aggregate roots in our domain and not for every single domain object. Access to other objects would be via the aggregate root which we could retrieve from one of the repositories.

This pattern can also be useful when we retrieve and store data via services which we have been doing recently. Of course eventually the data is stored in a database but much further up stream.

To start with we were doing that directly from our controllers but it became clear that although we weren’t interacting directly with a database the repository pattern would still probably be applicable.

The way we use it is pretty much the same as you would if it was abstracting an ORM:

repository.gif

I think with an ORM the mapping would be done before you got the data back so that’s an implementation detail that is slightly different but as far as I can see the concept is the same.

Written by Mark Needham

March 10th, 2009 at 10:31 am

DDD: Bounded Contexts

with 8 comments

I’ve been reading Casey Charlton’s excellent series of posts on Domain Driven Design recently and today came across his thoughts about which types of applications Domain Driven Design is suited to.

Towards the end of the post he talks about the fact that there is a lot of excellent ideas in Domain Driven Design even if you don’t have the chance to use all of them.

…there is a wealth of wisdom and experience encapsulated in Domain Driven Design – use what you think applies to your situation, and you will find your software becoming more flexible, more reactive to your audience, and easier to understand – just don’t expect miracles, and beware of over complicating your code for the sake of it – sometimes simpler really is better.

A pattern which I think is applicable in the majority of systems is bounded context – if I remember correctly this isn’t mentioned in InfoQ’s Domain Driven Quickly book but is extensively covered in the big blue book.

To quote the book with regards to what a bounded context is:

The delimited applicability of a particular model. BOUNDING CONTEXTS gives team members a clear and shared understanding of what has to be consistent and what can develop independently.

This means that a given model which we define is only valid in a specific part of our system. We would then have a layer of mapping between this bounded context and other parts of the system.

I’ve found this to be a really useful pattern to help reduce complexity where our application has integration end points. It makes it significantly easier to understand the code as you don’t need to keep all the context of what terms mean in other systems.

One thing that we discussed in our Domain Driven Design book club last week is that there are actually bounded contexts within the application itself as well as within the system as a whole.

For example if our application has a back-end database then that represents a relational model of the data in our system – that representation doesn’t make sense in other parts of the system and would typically be encapsulated from our code with the help of an ORM – the ORM effectively acting as an anti corruption layer between the database and our domain model.

I think we can also apply this with regards to the model we use on our user interfaces – often the model we display to our users differs from the one that makes sense to the business.

The only disadvantage of creating all these different bounded contexts is that we need to create mapping code between each of them, a job which can be pretty tedious at times.

On the other hand I think the advantages we get from having clearly defined areas where our various models are valid easily outweigh this in most cases.

Written by Mark Needham

March 7th, 2009 at 10:03 am