Different ways to implement 'dirty'-flag functionality [closed]

Almost every programmer did it once in his life: setting some flag if a variable's value changed. There's always lots of properties and you want to keep track if something changed

  1. in any property
  2. in a specific property
  3. or in some set of properties

I'm interested in different ways to implement the "dirty-flag" functionality for the above situations, besides the standard object wide dirty flag being updated on each property change. There must be something better than putting "dirty = true" in each setter: it just looks ugly and is a tedious work.


For my DAO I keep a copy of the original values as retrieved from the database. When I send it to be updated, I simply compare the original values with the current. It costs a little in processing but it is a lot better than having a dirty flag per property.

EDIT to further justify not having a dirty flag: if the property returns to its original value, there is no way to reflect that, the dirty flag continues dirty because the original value was lost.


I used to have a base Entity class, providing Dirty/Removed Logic.

When writing Entity-subclasses, you could do something like:

public string Name
{
    get { return name; }
    set { setValue("Name", value); }
}

This works fine, but has the 'ugly string' disease...

Today you can use Lambda Expressions to exclude the strings:

set {setValue(x => x.Name, value);}

Or, and I think that this is the best solution, you could use AOP:

https://www.postsharp.net/

This way, you can define actions by Attributes. You create an attribute and specify that when the user changes the associated property, the entity becomes dirty.

Additionally, you can keep a list of properties in your class (base Entity) which will remember the changed properties, and access that list from your AOP Code.


I've created a class called DirtyValue<T> which has an original value and a current value. On its first use it sets both the original value and the current value. Successive calls only set the current value.

You can tell if it has changed by comparing the two, with a readonly bool property called IsDirty(). Using this technique you can also get access to the original value as well.