Across here Colin MacKay has a good posting about using the Data Abstraction Layer pattern (DAL). That got me thinking, since I'm a bear of little brain, I like to keep things simple. A simpler pattern than DAL is the ActiveRecord pattern where the database function is a responsibility of the business object. This pattern (implemented below) is suitable for departmental (or smaller) scale applications.

namespace garyshort.org.patterns.activerecord
{
    /// <summary>
    /// GS - ActiveRecord implementation
    /// </summary>
    public class ActiveRecord
    {
        private int _Id = 0;

        public int Id
        {
            get { return _Id; }
            set { _Id = value; }
        }

        public void Save()
        {
            if (_Id > 0)
            {
                Update();
            }

            else
            {
                Create();
            }
        }

        public void Create()
        {
            //GS - Save object to db and insert returned Id
        }

        public void Read(int targetId)
        {
            //GS - Read row from db and fill in attributes
        }

        public void Update()
        {
            //GS - Save changes to db don't forget optimistic 
            //locking check
        }

        public void Delete()
        {
            //GS - Delete row from db where PK = Id
        }
    }

    /// <summary>
    /// GS - Impliment a business object that extends ActiveRecord
    /// </summary>
    public class BusinessObject : ActiveRecord
    {
        //GS - Business specific code here
    }

    /// <summary>
    /// GS - Implement a class to test our implementation
    /// </summary>
    public class Tester
    {
        public void Test()
        {
            BusinessObject bo = new BusinessObject();

            //GS - Set BO specific attributes here

            bo.Save(); //GS - Will call Create()

            //GS - Change specific BO attributes here

            bo.Save(); //GS - Will call Update()
            bo.Read(bo.Id);
            bo.Delete();
        }
    }
}
Technorati tags: ,