Social Icons

twitter google plus linkedin rss feed



The Clean Up Your Own Mess Pattern

Is this a pattern?

In most cases you want to change the value of a variable and leave it that way but in some occasions you want to change the value of a variable, perform some action and then set it back to whatever it was.

With this piece of code it's really easy and you are certain you won't forget. Ever.

The idea is to create a class that implements the IDisposable interface and saves the values to the state they were when we created it and set them to whatever we need to work. Later, in the Dispose, it changes back the variables to the initial values:
public class ManageAllowUnsafeUpdates : IDisposable
    private readonly bool allowUnsafeUpdatesStatus;
    private readonly SPWeb Web;

    public ManageAllowUnsafeUpdates(SPWeb Web)
        this.Web = Web;
        allowUnsafeUpdatesStatus = Web.AllowUnsafeUpdates;
        Web.AllowUnsafeUpdates = true;

    public void Dispose()
        Web.AllowUnsafeUpdates = allowUnsafeUpdatesStatus;

Using it later is as simple as:
using (new ManageAllowUnsafeUpdates(Web))
    ListItem[this.FieldName] = (String)value;

And you don't have to think any more if the value was set to true or false before because the class will manage that for you.

This is a silly piece code but I think serves well to demonstrate the idea.

No comments:

Post a Comment