Monday, December 5, 2011

Object Modelling Part 1 - Data Object

I think object modelling isn't new concept, in fact I learnt it somewhere and added in few ideas that I thought of.

The basic idea of object modelling is that each object represent a row record in a table. All the relationships between tables are mapped in the object so that data in table could be accessed via object without access to data again and again.

To illustrate the concept, consider the following ClassA ( in C#)
class ClassA{

  private String mId;
  private Hashtable _HshTable;

  public ClassA(String Id){
    mId = Id;
  }

  public String property1{
    
    get{
       _getString("property_1");
    }

    set{
       _setString("property_1", value);
    }

  }

  public void refresh(){
    //populate the object with data from DB based on primary key mId to _HshTable;
  }

  public void save(){
    //update everything back to DB based on primary key mId.   
  }

  private _getString(String strProperty){
     if (_HshTable == null) refresh();
     return _HshTable[strProperty];
  }

  private _setString(String strProperty, String strValue){
     if (_HshTable == null) refresh();
     _HshTable[strProperty] = strValue;  
  }
}

The advantages of using object modelling is that we do not need to write code to access the database and join the tables every time if needed. We can access the data via format below.

ClassA ObjA = ClassA("Id01");
String value = ObjA.property1; //get value
ObjA.property1 = "Another value"; //set value

We can access the data in much simpler and structured method.

The next step, we could build operation and relationship to the object. Operation is based on business model. The relationship of the objects also are modelled and we could use it again and again without access the database. It is good idea to separate it to another object, i.e. one object to deal with database and another object to deal with business. From there, we can have a strong base for future extension.

Object Modelling Part 2 - Business Object

No comments:

Post a Comment