Confused about state of new objects

Confused about state of new objects

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


stevevrporter posted on Wednesday, May 24, 2006

Hi all,

 

I’m very new to CSLA, but I’m excited about the potential.  My first task was to create some unit tests for the sample project included in the sample code, but I’m getting unexpected behaviour.

 

Here’s the test…

 

[TestMethod()]

public void CreationTest()

{

    Resource res = Resource.NewResource();

 

    Assert.IsFalse(res.IsValid, "new Resource is not valid.");

 

}

 

I expected the newly created resource to be invalid since it’s first name and last name are both empty (the private member variables are initialized to string.empty) and there is a business rule attached to this object that both of those values must not be empty.

 

But that’s not what happens.  It looks like the rules only get invoked once I attempt to set a property.  Is this the expected behaviour?  Should the object perform a validation after it’s created to make sure that it’s left in the correct state?  I added a couple of calls to PropertyHasChanged in DataPortal_Create and this addressed the issue, but I’m left wondering if I’m missing something bleedingly obvious.


Ta.

Steve Porter

 

nermin replied on Wednesday, May 24, 2006

I beleive I remember Rocky talking about this.  I think this behavior is by design.  In most of the cases you will have object either load its state from DB or be initialized in the Factory Method.

The results of both are presumed to be valid by default.  E.g. if you saved something to DB you must have validated it first, so therefore no need for validation.  Same is the case for the result of the Factory Method (after all you are initializing the fields to constants therefore you should know if they are valid or not).

Your approach of adding the calls in DataPortal_Create (after initializing the fields to the default values is a correct approach)

 

Nermin

stevevrporter replied on Wednesday, May 24, 2006

Howdy,

OK, that sounds familiar now. 

Hmm, is the better change to adjust the initializations to make the class valid?  That doesn't seem correct, but it seems to be more in line with Rocky's intent.


Ta.

Steve Porter

nermin replied on Wednesday, May 24, 2006

No, I don't think you want to do that.

I think Rocky just assumed that  most of the initial states are going to be valid, and therefore no need for overhead of validation by default.  If not, we can always call validation after setting the values. 

xal replied on Wednesday, May 24, 2006

If your object requires that the rules are checked upon creation, then you should be calling CheckRules() inside your dataportal_create().... (No need to call propertyhaschanged!!)

Andrés

stevevrporter replied on Wednesday, May 24, 2006

Brilliant!  That's just what I was looking for.  Thanks.

Copyright (c) Marimer LLC