C# .NET Programming Tip: Keeping A History With Properties

The program I am writing at work’s primary functionality is a checklist. One of the requested features is the ability to record what actions a user performs on the checklist. So there needs to be some additional code that updates a history table whenever a user makes any changes to the checklist.

Let’s define when a history event should fire off:
When the user makes a new checklist.
When the user updates any property of the checklist.
When a user archives a checklist (eg: discard in so many words).

Making a history entry when the user makes a new checklist or archives a checklist is easy. There would generally be only one function for each, so just before or after adding or archiving the checklist from the database, the history process is called.

What about when the user updates a single field in a checklist? It is important to track those changes, because a single little change is generally the most important (he said, she said situation).

In my program checklistprocessor, checklist, checklistitem, history, and database are all separate objects. So what would be an easy way to update each property individually and also record the before/after state in a history entry?

Use properties!

Here is an example of one such property:

class CheckListItem
{
   private int id;
   private int checkListId; //foreign key to CheckList
   private string notes;
   ...

   //will hold a reference that is received from a calling object
   private Database dbConnection;

   public string Notes
   {
       get { return this.notes; }
       set
       {
           //create history entry for this change
           History.add(id, checkListId, this.notes, value);

           //update instance variable
           this.notes = value;

           //update database with new value
           dbConnection.queryNoResult("UPDATE ... WHERE... ;")
       }
   }

   ...

Remember that C# is case sensitive. That means we can have a Notes property and a notes class variable. It makes things a lot simpler naming wise and is, from what I have read, an unofficial standard practice.

As you can see from the code, all the checklist has to do to update a checklistitem variable called “notes” is call the property Notes. Everything else is handled by the set method.


Posted

in

by