Wow – it seems like last year just flew by. I opened LiveWriter this morning and realised that I last posted an article in June 2011, and that I have 14 incomplete articles that I’ve never got round to completing.
To kick off the year, I’m going to start off with (what I think) is an underused class in Castle ActiveRecord (actually, it resides from NHibernate) – Disjunction.
The Disjunction type can be used to construct large 'OR' statements for use in ActiveRecord data retrievals. If you have used this class before, you may have noticed that any ‘OR’ operations that have more than two boolean operation that you’ve wanted to perform end up looking like this:
var criteria = Restrictions.Or
(
Restrictions.Or(Restrictions.Like("Firstname", "Foo"), Restrictions.Like("Lastname", "Foo")),
Restrictions.Or(Restrictions.Like("Firstname", "Bar"), Restrictions.Like("Lastname", "Bar"))
);
var person = Person.FindAll(criteria);
The example above ends up producing some unnecessary code clutter to essentially come up with the SQL statement:
WHERE
Firstname LIKE '%Foo%' OR
Firstname LIKE '%Bar%' OR
Lastname LIKE '%Foo%' OR
Lastname LIKE '%Bar%'
Using the Disjunction class, you can modify the original example to look like this:
var criteria = new Disjunction();
criteria.Add(Restrictions.Like("Firstname", "Foo"));
criteria.Add(Restrictions.Like("Firstname", "Bar"));
criteria.Add(Restrictions.Like("Lastname", "Foo"));
criteria.Add(Restrictions.Like("Lastname", "Bar"));
var person = Person.FindAll(criteria);
In my opinion: better looking code and, although it’s not quite made evident in the examples above, it makes for much easier programming. Image that you were searching 5 fields for three keywords – the “tree” that you’ve effectively built in the first example would start looking horrendous and would be a nightmare to maintain.