The Property Memento pattern

Edit: Find an improved implementation of the pattern here.
Edit
: Find an explicit implementation of the pattern here.

This blog post shows the Property Memento as pattern for storing property values and later restoring from those. Constructive feedback is welcome everytime!

Problem description

It’s a common task in several scenarios: you want to store the value of an object’s property, then temporarily change it to perform some actions and at the end restore the original property value again. Especially with UI-related task you come into this situation quite often.

The last time I came across with this requirement is only some days/weeks ago and was a UI task as well. I created a generic detail view in WinForms, which was built up by Reflection from an object’s properties and optional metadata information. This form contained a control for the object’s values on the one side and a validation summary control for showing validation messages on the other side. The validation summary had to change its content and layout dynamically while performing validation.

Through the dynamic nature of the form unfortunately I couldn’t use the AutoSize feature and thus had to layout the control manually (calculating and setting control sizes etc.). But I still wanted to use some AutoSize functionality, at least for the validation summary. And here’s the deal: everytime the validation messages on the summary change, the control should AutoSize to fit its content. With the new size I recalculate the Height of the whole form. This task can be done by manually setting the AutoSize property temporarily. Additionally it’s necessary to temporarily set the Anchor property of the details control and the validation summary to complete the layouting process correctly.

Normally in the past I would have used a manual approach like this:

private void SomeMethod(...)
{
    int oldValSumHeight = _valSum.Height;
    int newValSumHeight = 0;

    bool oldValSumAutoSize = _valSum.AutoSize;
    AnchorStyles oldValSumAnchor = _valSum.Anchor;
    AnchorStyles oldDetailAnchor = _detailContent.Anchor;

    _valSum.AutoSize = true;
    _valSum.Anchor = AnchorStyles.Left | AnchorStyles.Top;
    _detailContent.Anchor = AnchorStyles.Left | AnchorStyles.Top;

    _valSum.SetValidationMessages(validationMessages);

    newValSumHeight = _valSum.Height;
    Height = Height - oldValSumHeight + newValSumHeight;

    _valSum.AutoSize = oldValSumAutoSize;
    _valSum.Anchor = oldValSumAnchor;
    _detailContent.Anchor = oldDetailAnchor;

    _valSum.Height = newValSumHeight;
}

What a verbose and dirty code for such a simple task! Saving the old property values, setting  the new values, performing some action and restoring the original property values… It’s even hard to find out the core logic of the method. Oh dear! While this solution works, it has a really poor readability. Moreover it’s not dealing with exceptions that could occur when actions are performed in between. Thus the UI could be left in an inconsistently layouted state and presented to the user in this way. What a mess! But what’s the alternative?

The Property Memento

Better solution? What do you think about that (edit: find a better implementation here):

private void SomeMethod(...)
{
    int oldValSumHeight = _valSum.Height;
    int newValSumHeight = 0;

    using (GetAutoSizeMemento(_valSum, true))
    using (GetAnchorMemento(_valSum, AnchorStyles.Top|AnchorStyles.Left))
    using (GetAnchorMemento(_detailContent, AnchorStyles.Top|AnchorStyles.Left))
    {
        _valSum.SetValidationMessages(validationMessages);

        newValSumHeight = _valSum.Height;
        Height = Height - oldValSumHeight + newValSumHeight;
    }

    _valSum.Height = newValSumHeight;
}

private PropertyMemento<Control, bool> GetAutoSizeMemento(
    Control control, bool tempValue)
{
    return new PropertyMemento<Control, bool>(
        control, () => control.AutoSize, tempValue);
}

private PropertyMemento<Control, AnchorStyles> GetAnchorMemento(
    Control control, AnchorStyles tempValue)
{
    return new PropertyMemento<Control, AnchorStyles>(
        control, () => control.Anchor, tempValue);
}

Notice that the logic of SomeMethod() is exactly the same as in the first code snippet. But now the responsibility of storing and restoring property values is encapsulated in Memento objects which are utilized inside a using(){ } statement. GetAutoSizeMemento() and GetAnchorMemento() are just two simple helper methods to create the Memento objects, which support readability in this blog post, but nothing more…

So how is the Property Memento working conceptually? On creation of the Property Memento it stores the original value of an object’s property. Optionally it’s possible to set a new temporary value for this property as well. During the lifetime of the Property Memento the value of the property can be changed by a developer. Finally when Dispose() is called on the Property Memento, the initial property value is restored. Thus the Property Memento clearly encapsulates the task of storing and restoring property values.

The technical implementation of the Property Memento in C# uses Reflection and is shown below (edit: find a better implementation here):

public class PropertyMemento<TClass, TProperty> : IDisposable
    where TClass : class
{
    private readonly TProperty _originalPropertyValue;
    private readonly TClass _classInstance;
    private readonly Expression<Func<TProperty>> _propertySelector;

    public PropertyMemento(TClass classInstance,
        Expression<Func<TProperty>> propertySelector)
    {
        _classInstance = classInstance;
        _propertySelector = propertySelector;
        _originalPropertyValue =
            ReflectionHelper.GetPropertyValue(classInstance, propertySelector);
    }

    public PropertyMemento(TClass memberObject,
        Expression<Func<TProperty>> memberSelector, TProperty tempValue)
        : this(memberObject, memberSelector)
    {
        SetPropertyValue(tempValue);
    }

    public void Dispose()
    {
        SetPropertyValue(_originalPropertyValue);
    }

    private void SetPropertyValue(TProperty value)
    {
        ReflectionHelper.SetPropertyValue(
            _classInstance, _propertySelector, value);
    }
}

This implementation uses the following ReflectionHelper class:

static class ReflectionHelper
{
    public static PropertyInfo GetProperty<TEntity, TProperty>(
        Expression<Func<TProperty>> propertySelector)
    {
        return GetProperty<TEntity>(GetPropertyName(propertySelector));
    }

    public static PropertyInfo GetProperty<T>(string propertyName)
    {
        var propertyInfos = typeof(T).GetProperties();
        return propertyInfos.First(pi => pi.Name == propertyName);
    }

    public static string GetPropertyName<T>(
        Expression<Func<T>> propertySelector)
    {
        var memberExpression = propertySelector.Body as MemberExpression;
        return memberExpression.Member.Name;
    }

    public static TProperty GetPropertyValue<TEntity, TProperty>(
        TEntity entity, Expression<Func<TProperty>> propertySelector)
    {
        return (TProperty)GetProperty<TEntity, TProperty>(propertySelector)
            .GetValue(entity, null);
    }

    public static void SetPropertyValue<TEntity, TProperty>(TEntity entity,
        Expression<Func<TProperty>> propertySelector, TProperty value)
    {
        GetProperty<TEntity, TProperty>(propertySelector)
            .SetValue(entity, value, null);
    }
}

As you can see, the Property Memento implementation is no rocket science. The constructor gets the class instance and an Expression which selects the property from this instance. Optionally you can provide a property value that should be set temporarily in place of the original value. Getting and setting the property value is done via the ReflectionHelper class. For the sake of shortness the implementation doesn’t have a good error handling mechanism. You could employ your own checks if you want. What I like is the use of generics. This eliminates many error sources and guides a developer with the usage of the Property Memento.

Really a pattern and a Memento?

I’ve used the Property Memento now in several different situations with success and thus I think it’s justified to call it a pattern.

But is it a Memento as well? Wikipedia says about the Memento pattern:

„The memento pattern is a software design pattern that provides the ability to restore an object to its previous state […]“

And this is true for the Property Memento, where the „object“ equals a property value on a class instance! The „previous state“ is stored on creation of the Memento and „restore an object“ is done on call of Dispose().

Finally

This blog post has shown the Property Memento as pattern for storing original property values and later on restoring them.

Compared to the „manual way“ the Property Memento has valuable advantages. It encapsulates the responsibility of storing an original value and restoring it when the using() block is finished. Client code remains clean and is condensed to the core logic, while delegating responsibilities to the Property Memento by an explicit using(){ } block. Thus the code becomes much more concise and readable. Last but not least the Property Memento employs an automatic exception handling mechanism. If an exception occurs inside a using() block of the Property Memento, finally the Dispose() method is called. Thus the Property Memento restores the original property state even in exceptional situations and the user gets a consistent layouted UI.

kick it on DotNetKicks.com

Code Contracts #6: Modelling constraints and state

(Note: this article has been updated on 2009/05/16 by replacing the example and adding some more information)

Modelling constraints on class properties and valid state of classes explicitly is an interesting topic and sometimes I catch myself being frustrated by the lack of handling these aspects through current programming languages. With „constraint“ I mean a condition on one class property or on a set, which equals a subset of the properties for the class. The same is true for the „state of a class“. Periodically I run into situations, where I have for example two properties, whose values depend on each other. And what I want is to express explicitly, that when property 1 is in state X, then property 2 must be in state Y and vice versa and that this constraint on those properties (their depending state) mustn’t be broken!

Let’s consider a (very) little example in form of the following class MinMax:

public class MinMax
{
    public int MinValue { get; set; }
    public int MaxValue { get; set; }
}

Not too impressive, isn’t it? 😉 But as you can imagine, there is one obvious constraint: MinValue <= MaxValue. Two other constraints are related to each property for itself – they mustn’t be less than 0: MinValue >= 0 and MaxValue >= 0 must be true. If those 3 conditions are true, then the class can be seen to be in a valid state. And in this case, we want to ensure this valid state all the time. The question follows quickly: How to model these constraints? Normally, you as programmer wouldn’t be very concerned about that. For example, in the setters of MinValue and MaxValue, you would check the constraints and throw an exception, if they don’t hold:

public class MinMax
{
    private int _MinValue;
    public int MinValue {
        get { return _MinValue; }
        set
        {
            if (value %gt; MaxValue)
                throw new ArgumentException("value can't be greater than MaxValue");
            if (value < 0)
                throw new ArgumentException("value can't be less than 0");

            _MinValue = value;
        }
    }

    private int _MaxValue;
    public int MaxValue
    {
        get { return _MaxValue; }
        set
        {
            if (value < MinValue)
                throw new ArgumentException("value can't be less than MaxValue");
            if (value < 0)
                throw new ArgumentException("value can't be less than 0");

            _MaxValue = value;
        }
    }
}

There’s an even better way, when you use a Guard class for that. Better, because you’ve outsourced the exception throw into the guard and you can do additional things there like logging something:

public class MinMax
{
    private int _MinValue;
    public int MinValue
    {
        get { return _MinValue; }
        set
        {
            Guard.Against<ArgumentException>(
                value > MaxValue, "value can't be greater than MaxValue");
            Guard.Against<ArgumentException>(
                value < 0, "value can't be less than 0");

            _MinValue = value;
        }
    }

    private int _MaxValue;
    public int MaxValue
    {
        get { return _MaxValue; }
        set
        {
            Guard.Against<ArgumentException>(
                value < MinValue, "value can't be less than MaxValue");
            Guard.Against<ArgumentException>(
                value < 0, "value can't be less than 0");

            _MaxValue = value;
        }
    }
}

public static class Guard
{
    public static void Against<TException>(bool assertion, string message)
        where TException : Exception
    {
        if (assertion)
            throw (TException)Activator.CreateInstance(typeof(TException), message);
    }
}

So it seems to be pretty easy to handle our constraints, right? Please don’t just take this stupid example into account. Imagine more complex cases, where you have numerous constraints on your class properties (one property or more than one depending properties), which aren’t far so obvious as in this example. Can you imagine the problems which arise, when you model them implicitly?

What if we would have a mechanism to model such (depending) property constraints explicitly, thus expressing valid class states? This would have some interesting advantages. First it helps you as programmer in creating and extending your class by ensuring that the constraints are maintained. Second it works as checked documentation for your code. If other programmers are extending your class, they would be aware of the constraints. By making things explicit and code-checked, it’s ensured that your classes are in valid state at every time by watching the defined constraints. Take MinMax as an example yet again. If you or another programmer is extending the class, you are not forbidden to write _MinValue and _MaxValue directly, thus going around the „state maintainers“ in form of the setters in MinValue and MaxValue and the calls to Guard. This example is small enough to not getting confused, but in more tricky cases the class could be left easily in an inconsistent state and yield more problems. An explicit model could lead a way out of that! Third when you distribute your components to third-party users, you would yet again reveal your intent by making the constraints of the class explicit. Users would be aware of them and could easier reproduce the behavior of your components. Hence there’s a much better chance that they use your class in a proper way from the beginning.

Do we have a mechanism to model such things? First if we think about class state, perhaps the GoF State pattern comes into mind, but that doesn’t fit our needs. It doesn’t have the power to make constraints explicit and model valid class state. But we can use Code Contracts for that! Object invariants (= invariants on classes) are exactly what we need. Object invariants give us the power to model constraints on classes explicitly, check them at compile and/or runtime (using the static or dynamic checker) and moreover allow us to define them on interfaces and abstract classes! Implementing/deriving classes must maintain the defined invariants and are allowed to make them stronger (but not weaker). So how would our MinMax-class look with that? Let’s see:

public class MinMax
{
    public int MinValue { get; set; }
    public int MaxValue { get; set; }

    [ContractInvariantMethod]
    protected void ClassConstraints()
    {
        Contract.Invariant(MinValue >= 0);
        Contract.Invariant(MaxValue >= 0);
        Contract.Invariant(MinValue <= MaxValue);
    }
}

That’s really small and seems to be pretty, doesn’t it? With the ContractInvariantMethod we can declare a method that contains the invariants/constraints of the class, which must be maintained by every class method (including get/set on properties). This method and its checks are run on exit of every other class method. With Contract.Invariant() you’re able to define an invariant. It doesn’t matter if there are simple cases as here or more complex cases on depending properties (for example implications) – every boolean expression can be modelled with that.

However somebody could find some issues with this example, so let’s explain. The above code is pretty, because the constraints are outsourced to one single method (thus avoiding redundancies) and you haven’t to take care of calling this method everytime (because Code Contracts will call it for you on exit of every other method).
As first issue, callers (clients) of the MinValue.set and MaxValue.set methods don’t see directly which values are allowed, because it’s not part of the method contract (the preconditions on the setters). In this example it’s ok, because he can look at the invariants (the contract of the whole class) and see, which values are allowed. So this issue is weak here, but in other method cases you really have to duplicate invariants with preconditions, what is some kind of ugly.
Second, the static checker will not be happy with that code, because it’s aware of that you can provide some invalid value in the setters. That’s an issue of Code Contracts itself and I hope the team will come up with some further development to handle this case automatically. So this issue is weak as well.
The third issue seems to be stronger. If an invariant is broken and hence a ContractException is thrown, the wrong value will remain in the current MinMax instance, if you handle the exception outside with try/catch (MinMax is left in an invalid state). If you don’t use the object anymore, that’s no problem, but else you have no chance to go to the state before the exception was thrown, except you’re handling that on your own in the caller/client. Is this a really good issue? Again, it’s not. This issue goes away, if we look at the purpose and behavior of DbC for this case. In DbC the client is responsible for ensuring preconditions when calling a method and if it comes to properties, he has to respect the invariants, too. If the client breaks a method’s contract, then the method itself is not obligated to ensure defined behavior – it’s simply undefined. And since contracts should be compiled out from the release version (while debugging and testing has been run before), that’s no problem at all. The break of a contract means the presence of a bug. The client should not handle such a case (handle the bug) by catching the exception and then further using the object. The object should be thrown away and the client must take care to call the method in a proper way.
As you can see, there are no definite issues with this example. Fortunately for true, because including preconditions in every setter would have meant to duplicate assertions as preconditions and invariants and this would destroy the advantage of having minimal check redundancies compared with the concept of defensive programming.

This article has shown some interesting aspect of Code Contracts. Modelling constraints (on (depending) properties) and valid class states is not handled very well by programming languages and easily yields to various coding problems, since your intention isn’t made explicit and valid class state isn’t checked automatically. Code Contracts can help us in this case very well by the use of object invariants. One more time making things explicit helps you as programmer and other programmers that use or extend your components.

kick it on DotNetKicks.com

Code Contracts #5: Method purity

After getting some things done, now I’m returning to Code Contracts. In the first parts of this series I gave you some basic information about Code Contracts, the static and dynamic checker, the code rewriter and how implications can be modelled. This day’s blog post comes up with another interesting aspect: method purity. There seems to be some misunderstanding on this term – I want to clear some clouds and show you what method purity means and which implications it has.

Code Contracts come with an attribute called [Pure] for decorating class methods (and by which you can declare a method as being „pure“). Method purity is a quality, expressing that the method is free of observable side effects. This means, it does not change the observable state on any objects seen by callers in some way. For example, pure methods do neither modify properties of a class nor reference type method arguments. Even the modification of a private field (which is not seen by callers directly) is prohibited, if class methods work with this field and return values, that depend on it. In this case the change of the field is indirectly reflected by a changed method return value, thus the observable state has changed! To summarize, mostly pure methods are only allowed to change objects that have been created after method entry.

The following code shows the simple class Point and gives you a short example of how to use Pure in declaration and pure method calls in contracts. The static and dynamic checkers will both be very happy with that 🙂 :

public class Point
{
    public int X { [Pure] get; set; }
    public int Y { [Pure] get; set; }

    public Point() { }

    [Pure]
    public double GetDistance()
    {
        return Math.Sqrt(X * X + Y * Y);
    }

    public void SwapXY()
    {
        Contract.Ensures(Contract.OldValue<int>(X) == Y);
        Contract.Ensures(Contract.OldValue<int>(Y) == X);
        Contract.Ensures(Contract.OldValue<double>(GetDistance()) == GetDistance());

        int temp = X;
        X = Y;
        Y = temp;
    }
}

(Perhaps not the best example, because we have redundant information in code and contracts in SwapXY() – that should not be the goal in most cases, but in this simple scenario it’s quite ok for demonstration purposes)

 

All methods that are called within a contract (pre-/postcondition etc.) must be declared pure. But why?

First it has a very certain reason: contracts like the Contract.Requires() and Contract.Ensures() assertions will not be evaluated in every execution and build configuration. For example, you can choose just to check pre-conditions, thus stepping over the post-conditions. I don’t need to explain, that methods with side effects in those post-conditions would be a messy thing. The execution results of your code would depend on the configuration of Code Contracts and if the contracts are evaluated – this must be prohibited and that’s why all methods called in contracts must be pure. Remember that Code Contracts is declarative code. It should not influence the behavior of your code, but just decorate it in some way.

Second, declaring methods as pure is generally a good thing. Beside of allowing you to use those methods in contract declarations, it furthermore helps the static checker in its task. Since method arguments can not be changed arbitrarily in pure methods, the static checker can assume that those objects will be the same after the method call.

Third (and for me that raises Code Contracts to an even higher level), declaring a method as pure can yield to a better software design and just clarifies your intent. You as programmer are able to express explicitly that your method does not have side effects. The intention of the method is revealed to callers (intention revealing), who can rely on the fact, that the state of the method’s class will be the same after calling the method as before. Thinking about declaring as many methods as possible as pure quickly brings us to command-query-separation, where you are trying to have exactly two types of methods. On the one handside the commands, which change class state and on the other handside queries, which calculate some value from current class state, but don’t modify it. Thus, queries are pure methods and with the [Pure] attribute you are able to explicitly express this intention. Dividing commands/queries and expressing queries with [Pure] is often (while not everytime) a good thing, since it leads to clear design and distinct intention and let you avoid side-effecting methods, which can be horrible code smells indeed (think of deep-nested side-effecting methods, for example).

Currently there is no component of Code Contracts which checks if methods declared pure are pure indeed. Thus if a programmer decorated a method with [Pure], it’s just believed. The Code Contracts team is working heavy on that, thus to come up with a purity checker in a future release.

(Update: thanks to AJ, I clarified my intent with the following section) Moreover one may ask: Are there any implications to automatic parallelism? The answer is: not directly. Parallelism is a hot topic and one could think, that method purity brings automatic parallelism of calls to such methods to life. And purity is indeed a strong characteristic of a method, but it’s not sufficient for the auto-par task. It’s just a one-way road, since it declares, that a method is side-effect-free (thus it doesn’t write any shared state). But in general a method can also read shared objects and depending on this it could return another value. Thus, parallelism of those method’s calls could run into problems (returning non-expected values), if the state is changed by other methods between subsequent calls. Perhaps there will be more attributes similar to [Pure] for such use cases in the future or other structures to handle that? I’m a believer…

So far for now on this topic. As you can see, decorating your methods in a declarative way with attributes like [Pure] can express your intent in a very smooth way. It helps you to clarify your design and it helps other programmers to know your intent – not just by code comments, but by checked documentation via Code Contracts.

kick it on DotNetKicks.com