Wednesday, July 11, 2012

Simple Extension Methods (part 3)

One very common task when one is implementing the business logic in Common project is writing custom PropertyName_Changed partial methods.
This “approach” has an undesired “side-effect” when the property is an entity property (as compared to screen properties). The property changes many times during the lifetime of the object. While loading, while deleting etc., whereas what we want to implement is handle the “actual” property changes caused either by the user or by some other piece of business logic.
I found myself debugging code that shouldn’t be executing (according to my logic, obviously LS had another opinion) before ending up writing a small extension method to use in all PropertyName_Changed partial methods. I don’t claim this method will help you avoid ALL unwanted business logic code execution, but covers most of the cases. I would be glad to read any comments improving it in a generic way.
Here is the code of the extension method:
public static bool IgnorePropertyChange(this IEntityObject entity) {
  return entity.Details.EntityState == EntityState.Unchanged ||
         entity.Details.EntityState == EntityState.Discarded ||
         entity.Details.EntityState == EntityState.Deleted;
}




And here how all my property changed partial implementations for entity properties look like
partial void ScheduledEndDate_Changed() {
  if (this.IgnorePropertyChange())
    return;
  .
  .
  .
}



This looks (and is) simple but the concept, alone, of “unwanted” code execution is important and should be taken good care of. If not using this extension method any other way one may like Winking smile.

1 comment:

  1. Where would one place exactly the Class Extension code, in LS VS 2013?
    We no longer have the "Common" project.
    Thank you

    ReplyDelete