ActiveRecord

Building a business layer for an application always seems to have a large percentage of code that you could class as plumbing. Things like getters and setters for properties and search type operations. Reading an article by Bruce Tate about the ActiveRecord framework within Rails I was met with a big suprise. Using the ActiveRecord framework with Ruby creating a business object to represent a person looks like this:

class Person < ActiveRecord::Base
end

Yep, that is all you need to write and you get a class with:

  • first_name and a last_name properties for all properties of the object
  • save type methods
  • search methods, eg find_by_last_name

What is giving us this is a simple design pattern called ActiveRecord that relies on the assumption that your business objects mirrors the structure of your database tables ie the person object has a corresponding person table in the database.

The ActiveRecord framework within Rails follows a trait that seems to apply to most ruby development, is that by following a convention there is no need to enter configuration information. In the person class example by having a primary key called id and not changing the search standard of find_by_<fieldname> we don’t need to configure the framework it just does it all for us. ORM mapping tools like Hibernate rely on entering configuration information to make them work.

The fact that Ruby is a Dynamic language also brings alot to the table in that we haven’t had to generate any code to comply with a static language. The person object we get has properties for each field in the table and supports the table being updated. In the article Bruck looks at implementing something similar in Jave but you end up with a method like person.get(name) which create smore problems that it solves.

The ActiveRecord framework takes a very pragmatic approach to the problem of creating a business layer in that it doesn’t try to be the solution to all problems. It is a good example of the 80-20 rule in that 80% of problem can be solved with 20% of effort, go outside of the 80% that Active record. You have to deal with the 80% of effort to solve the other 20%.

Very nice!

Advertisements

Tags:

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: