DataPortal_Create vs. Parameterized Constructor in EditableChild

DataPortal_Create vs. Parameterized Constructor in EditableChild

Old forum URL: forums.lhotka.net/forums/t/2750.aspx


JabbaTheNut posted on Sunday, April 22, 2007

I have an EditableChildList object called UserRoles that contains a collection of UserRole objects.  I need to create each UserRole using parameters.  Is there a difference between the following methods (i.e., which one is preferred)?

*********** METHOD 1 **************

internal static UserRole NewUserRole (int userID, int roleID)

{

      return DataPortal.Create<UserRole> (new Criteria (userID, roleID));

}

private UserRole ()

{

      MarkAsChild();

}

private void DataPortal_Create (Criteria criteria)

{

      // Load data from database based on parameters contained in criteria.

}

*********** METHOD 2 **************

internal static UserRole NewUserRole (int userID, int roleID)

{

      return new UserRole (userID, roleID);

}

private UserRole (int userID, int roleID)

{

      MarkAsChild();

      // Load data from database based on supplied parameters.

}

boo replied on Sunday, April 22, 2007

Yes.  The purpose of DataPortal_Create is so that the creation occurs on the application server, where as your second example would occur on the client machine. 

You should always do your creation/update/deleting of object through DataPortal methods...i.e. you shouldn't ever access the database if it's not initiated from the one of the DataPortal_XYZ methods.  Not only is it consistant with how CSLA is intended to be used, but it will also allow you to not have to re-code things should you ever go to a N-Tier physical architecture.  The idea is that the client machine may not have access to a resource, but the server will, the DataPortal_XYZ methods run on the server.

If you're create method doesn't do anything spectacular that it would need to get values from a data source you can always supply the RunLocal() attribute to the method.

HTH

RockfordLhotka replied on Monday, April 23, 2007

Typically the data portal is only used for root objects.

While you can technically use the data portal for child objects, there's no value to doing so, and so I recommend against it. Instead, I recommend using the coding style from the book, where the parent calls a Friend/internal factory method on the child, that factory method calls the constructor and the constructor calls a private Create() or Fetch() method to do the actual data load.

If you want, you can skip the factory method and have the parent call the ctor directly, but I prefer to use the factory to keep a higher level of consistency in how the objects are created. Consistency leads to maintainability, and maintainability is the light side of OO Smile [:)]

Copyright (c) Marimer LLC