When ActiveRecord, when (Fluent) NHibernate?

I’ve recently been working on a fairly straight forward WCF Web-Service using Castle ActiveRecord, which uses NHibernate under the hood.

So far, I’ve been really impressed with ActiveRecord as a well throught through abstraction of NHibernate’s key features, which does a great job of keeping you focussed on the important stuff, without getting bogged down in the config.

I don’t want to go into depth on this here, but just to give you a quick idea if you haven’t seen this before, you simply add the attributes to your entities to describe how you want them persisted:

1
2
3
4
5
6
7
8
9
10
11
12
13
[ActiveRecord]
public class UpdatePersonMessage : BaseObject
{
    [PrimaryKey(Generator=PrimaryKeyType.GuidComb)]
    public virtual Guid Id { get; set; }
 
    [Property(Length = 50)]
    public virtual string FirstName { get; set; }
 
    [Property(Length = 50)]
    public virtual string LastName { get; set; }
    ...
}

You can then get ActiveRecord to dynamically create your database on initialisation, with a single line of code:

1
ActiveRecordStarter.Initialize(typeof(UpdatePersonMessage));

OR, if you want to use a custom config location… (I’ve had to format a little strangley to prevent this scrolling)

1
2
3
4
IConfigurationSource config = 
      new XmlConfigurationSource("{pathto}/ActiveRecord.config");
ActiveRecordStarter.Initialize(config, 
      typeof(UpdatePersonMessage));

So, on the last coulpe of projects where I’ve used ActiveRecord, I’ve been thinking – when would I bother using NHibernate, having to create all the relevant XML mapping files either by hand, or via a tool such as MyGeneration, or by using the declarative API for configuration provided by Fluent NHibernate?

As far as my experience tells me, there are only just a few key questions you can ask that can help you decide whether or not:

Please note: this already assumes that a full ORM is the appropriate solution for your domain – see YAGNI principle if you are not sure

  1. How complex is your data model? (e.g. beyond 3NF/BCNF, or complex legacy)
  2. Is this is a sensitive legacy datasource, tightly coupled to other legacy applications?
  3. How many people will be making changes to the data model, and how often?

The more complex the requirement, the more you move away from a situation that would get the best out of ActiveRecord. The approach is deliberatly simple, and while the pattern can cope with most day-to-day projects, as soon as your data requirements become more bespoke, it could be worth reconsidering an approach using NHibernate nativley.

Mapping files, attributes or declarative C#

Almost treated as a secondary design decision is how to manage the mapping of your data model.

If you use XML configuration files with a large team who all have access and make frequent changes, it can be a nightmare to manage. and you’ll quickly find yourself in the situation where you’ll be wondering why a particular persistence routine isn’t producing the expected behaviour anymore, and it’s simply down to a change you were not aware of.

Obviously TDD can really help with this, as can limiting access to just a couple of key developers who take ownership of the data model (and lock the mappings section down in source control!). On most projects, a data architect or lead dev would already have been allocated this role anyway.

Managing the mapping using C# code (e.g. using Fluent NHibernate) is often the best alternative if you’re not using ActiveRecord (or another configuration abstraction layer) for a number of reasons:

  1. No Type-Safety = runtime explosions
  2. No Intellisense
  3. Your code will always compile regardless of how present, or correct your mapping files are

Here’s an example of Fluent NHibernate in action:

1
2
3
4
5
6
7
8
9
10
public class UpdateExhibitorMessage : BaseObject
{  
    public UpdatePersonMessage()  
    {  
        Id(x => x.Id);  
        Map(x => x.FirstName);  
        Map(x => x.LastName);
        ...
    }  
}

then, using the Auto Persistence Model – you can create the schema in the much same way as ActiveRecord:

AutoPersistenceModel.MapEntitiesFromAssemblyOf<UpdatePersonMessage>().Configure(config);

Summary

I have to admit… this has been a rushed post and none of these ideas are particularly new, but my aim is really to make it clear that there are several different decisions involved in getting the right NHibernate implementation to suite your problem domain and your team that begin AFTER you’ve made the decision to use NHibernate, and each of these decisions need to be thought through carefuly, because – as with software development in general – there is never a one-size-fits-all approach.


Quick Post-Edit Note: Be weary of any developer suggesting you use a particular pattern or framework with being able to solidly defend the specific benefits to your current solution. I know it sounds obvious, but it’s crazy how often you come across “CV++” or developers sticking to ‘what they used on their last project’ without choosing the approach that is the right fit for your current domain.

Free tests on Brainbench!

Some great free tests available on Brainbench this month (April 2009):

Life-changing Software

Casey @ Devlicio.us posted an interesting point the other day, discussing the lack of any real positive impact we software developers actually have on the world (other than lining already bulging blue-chip pockets), which led to an interesting discussion, which I’ve quoted here:

Job Satisfaction, And Making The World A Better Place

You know what we achieve with all our wonderful software patterns and practices? Not a lot on the whole.

We do fairly well financially out of it, and many of those who use our software do fairly well financially from it too. A select few of us write software that can have a small impact on the well being of others, but even then, it is in a totally detached way.

But how often can you say that your day at work has affected somebody else’s life for the better, or made a really positive change to the world? How often can you look in the mirror and say my whole day was spent helping other people?

So, what the hell am I doing in the software game? Well, like I suspect many of us, I fell into it by accident. It was my hobby at school, I wrote games software and made a fairly comfortable (for a schoolboy) living from doing it.

Although my choice of O Levels (equivalent to GCSEs these days) were picked around becoming a doctor, and even though my mother had to argue with the school for weeks to get them to allow me to do three sciences, home and family circumstances at that time meant I never actually took most of my school exams. So with nothing in the way of real qualifications, I drifted into what I was naturally good at – technical support and writing computer software. My hobby turned into
my career.

Twenty odd years later, and I am more than comfortable with my career, I like to think I am pretty good at it. I also still often think, I could have been adding much more value to other people’s lives if I had stuck with my original choice. Recently I met a lady who was a nurse, and I was totally inspired by her and how much satisfaction she clearly got from her work – she told me that I could still retrain even at this stage in life.

Now I expect you are waiting for some kind of development related conclusion here … but unfortunately there isn’t one. What there is, is a small realisation that I could probably be doing something more for the world.

So, I have started seriously investigating my options for a radical career change – and to retrain as a medical doctor. Now this isn’t quite my swansong from development just yet. Not only do I have some major considerations to make, but I also have to put enough money aside to finance this shift, and after all that I have to succeed in an application to medical school, which in the UK is a very difficult task indeed, as places at our universities are very sought after, and the universities can afford to be very selective. I could even do one or two years getting the entry requirements, only to fail to get a place at medical school.

But, I have started sending off enquiries to various universities asking for their advice on the best route in, and perhaps it will pay off. It will be time consuming, financially very hard in the short
term, but it could be the most rewarding thing I could possibly do.
Ultimately, Job Satisfaction is About More Than Financial Reward

Whatever I eventually do, I have made a decision to get out and start giving back something to the world, maybe that will be with 6 years of medical training, followed by years of excessively long hours for very little pay … or maybe it will be just finding ways to make people’s lives better while continuing my career in software.

I encourage you all to find something positive you can give back to the world – the development community has some incredibly smart and insightful people – let’s not waste all our efforts on arguing over whether we should invert our dependencies or not!

And if you want somewhere to start doing your small bit, can I suggest you take a read of The Girl Next Door by Bil Simser

Bloody hell that was DEEP!”

And my response:

Sid M wrote re: Job Satisfaction, And Making The World A Better Place on 04-02-2009 9:45 AM

Great post Casey! This is something I’ve often found myself pondering and I think it’s fantastic that you have the impetuous to go and do something dramatically different! I really admire that. Also, I share your distaste of people who would waste precious hours debating obscurity as if were somehow the key to the universe!

However, I do think there is real value to be found in software development (despite Scott’s post which missed the point somewhat). Lives have definitely been saved by software (keyhole surgery equipment requires software, as do dialysis machines, 4d radar scanners and many other types of equipment and domains critical to the medical profession).

It’s not just medical software either; Families have been brought closer as software has aided cheaper, more lucid communication (video conferencing, IP telephony, Messenger, Skype, etc) and children are being introduced to a greater wealth of information about the world around them than has ever been available before, aiding their education. The list definitely goes on…

I think the key problem is that most of us don’t find ourselves participating in that kind of life-impacting software development, but it doesn’t mean we can’t! If, like me, you really enjoy software development, but unlike Casey, you don’t wish to dramatically change direction (for whatever reason), then why not try moving closer to the part of your industry where you see value being added… and join in! If that’s not palatable either, then why not think of a way you could use software to impact people’s lives positively… build it and release it yourself!

Software definitely doesn’t have to be about making the rich richer, or building yet another meaningless, under-used application for a blue chip client. Software can (and should be) about pioneering new ways to use technology to make our lives better and more enjoyable and I believe that offers a very broad horizon of possibilities, many of which can add real value to people’s lives.

Blog got wiped…

Looks like I’m starting again due to my WP database being the ONLY database I didn’t add to the backup schedule. Doh! The punishment for my school boy error? I have to start all over again. :-(