Active Record Design Pattern Doesn't Require Static Finder Methods

Active Record Design Pattern Doesn't Require Static Finder Methods

by David Hayden ( Sarasota .NET Developer )

The Active Record Design Pattern that I have talked about in a few posts:

describes an object that encapsulates a row in a database table or view. The object has the ability to read and write itself to the datastore as well as contains domain logic. As I mentioned in the previous Active Record Posts, it is most successful with forms-over-data applications, where you have simple business rules and the database model is the domain model. For these types of projects you will use some type of code generation and/or O/R Mapper to generate the classes for you, which contain mostly data access code.

For convenience, you will often find Static Finder Methods on these classes to wrap common queries that return Active Record Objects. I say convenience, because it has become a common practice to use static finder methods. Static finder methods on the class will probably be the first place a developer will look to find such functionality when you tell them you are using the Active Record Design Pattern.

However, you don't need to use static finder methods. You could use a separate class. Hence, you could have a Customer Class and a CustomerFinder Class. The Customer Class would represent a single row in a database table that can read and write itself to the datastore. When you want to find a customer or a collection of customers, you could execute instance methods on the CustomerFinder Class.

 

public class CustomerFinder : ICustomerFinder
{
    private IDatabase _database;
    
    public CustomerFinder()
    {
        _database = DatabaseFactory.CreateDatabase();
    }
    
    public CustomerFinder(IDatabase database)
    {
        Validation.AssertIsNotNull(database);
        _database = database;
    }
    
    public Customer FindById(int id)
    {
        ...
    }
    
    public Customer FindByEmailAddress(...)
    {
        ...
    }
    
    public CustomerCollection FindByState(...)
    {
        ...
    }
}

 

Whether you want to create a separate finder class is up to you. My only point is that Active Record does not require you to have static methods. It is pure convenience. If the static methods get in your way, move them to a separate class.

Source: David Hayden ( Sarasota .NET Developer )

Filed: Design Patterns

 

posted on Friday, September 01, 2006 11:21 AM

Main

News

Green Tea

.NET Development

Enterprise Library

Patterns & Practices