{"id":975,"date":"2010-08-11T10:22:30","date_gmt":"2010-08-11T09:22:30","guid":{"rendered":"http:\/\/www.minddriven.de\/?p=975"},"modified":"2010-09-12T13:45:39","modified_gmt":"2010-09-12T12:45:39","slug":"property-memento-pattern","status":"publish","type":"post","link":"https:\/\/www.minddriven.de\/index.php\/technology\/development\/design-patterns\/property-memento-pattern","title":{"rendered":"The Property Memento pattern"},"content":{"rendered":"<p><em><strong>Edit<\/strong>: Find an improved implementation of the pattern <a href=\"http:\/\/www.minddriven.de\/index.php\/technology\/development\/design-patterns\/property-memento-followup\">here<\/a>.<\/em><em><strong><br \/>\nEdit<\/strong>: Find an explicit implementation of the pattern <a href=\"http:\/\/www.minddriven.de\/index.php\/technology\/development\/design-patterns\/explicit-property-memento\">here<\/a>.<\/em><\/p>\n<p>This blog post shows the Property Memento as pattern for storing property values and later restoring from those. Constructive feedback is welcome everytime!<\/p>\n<h3>Problem description<\/h3>\n<p>It&#8217;s a common task in several scenarios: you want to store the value of an object&#8217;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.<\/p>\n<p>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&#8217;s properties and optional metadata information. This form contained a control for the object&#8217;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.<\/p>\n<p>Through the dynamic nature of the form unfortunately I couldn&#8217;t use the <code>AutoSize<\/code> feature and thus had to layout the control manually (calculating and setting control sizes etc.). But I <em>still<\/em> wanted to use some <code>AutoSize<\/code> functionality, at least for the validation summary. And here&#8217;s the deal: everytime the validation messages on the summary change, the control should <code>AutoSize<\/code> 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 <code>AutoSize<\/code> property temporarily. Additionally it&#8217;s necessary to temporarily set the <code>Anchor<\/code> property of the details control and the validation summary to complete the layouting process correctly.<\/p>\n<p>Normally in the past I would have used a manual approach like this:<\/p>\n<pre class=\"brush:csharp\">private void SomeMethod(...)\r\n{\r\n    int oldValSumHeight = _valSum.Height;\r\n    int newValSumHeight = 0;\r\n\r\n    bool oldValSumAutoSize = _valSum.AutoSize;\r\n    AnchorStyles oldValSumAnchor = _valSum.Anchor;\r\n    AnchorStyles oldDetailAnchor = _detailContent.Anchor;\r\n\r\n    _valSum.AutoSize = true;\r\n    _valSum.Anchor = AnchorStyles.Left | AnchorStyles.Top;\r\n    _detailContent.Anchor = AnchorStyles.Left | AnchorStyles.Top;\r\n\r\n    _valSum.SetValidationMessages(validationMessages);\r\n\r\n    newValSumHeight = _valSum.Height;\r\n    Height = Height - oldValSumHeight + newValSumHeight;\r\n\r\n    _valSum.AutoSize = oldValSumAutoSize;\r\n    _valSum.Anchor = oldValSumAnchor;\r\n    _detailContent.Anchor = oldDetailAnchor;\r\n\r\n    _valSum.Height = newValSumHeight;\r\n}<\/pre>\n<p>What a <strong>verbose and dirty code<\/strong> for such a simple task! Saving the old property values, setting\u00a0 the new values, performing some action and restoring the original property values&#8230; It&#8217;s even hard to find out the <strong>core logic<\/strong> of the method. Oh dear! While this solution works, it has a really <strong>poor readability<\/strong>. Moreover it&#8217;s not dealing with <strong>exceptions<\/strong> 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&#8217;s the alternative?<\/p>\n<h3>The  Property Memento<\/h3>\n<p>Better solution? What do you think about that (<em>edit: find a better implementation <a href=\"..\/index.php\/technology\/development\/design-patterns\/property-memento-followup\">here<\/a><\/em>):<\/p>\n<pre class=\"brush:csharp\">private void SomeMethod(...)\r\n{\r\n    int oldValSumHeight = _valSum.Height;\r\n    int newValSumHeight = 0;\r\n\r\n    using (GetAutoSizeMemento(_valSum, true))\r\n    using (GetAnchorMemento(_valSum, AnchorStyles.Top|AnchorStyles.Left))\r\n    using (GetAnchorMemento(_detailContent, AnchorStyles.Top|AnchorStyles.Left))\r\n    {\r\n        _valSum.SetValidationMessages(validationMessages);\r\n\r\n        newValSumHeight = _valSum.Height;\r\n        Height = Height - oldValSumHeight + newValSumHeight;\r\n    }\r\n\r\n    _valSum.Height = newValSumHeight;\r\n}\r\n\r\nprivate PropertyMemento&lt;Control, bool&gt; GetAutoSizeMemento(\r\n    Control control, bool tempValue)\r\n{\r\n    return new PropertyMemento&lt;Control, bool&gt;(\r\n        control, () =&gt; control.AutoSize, tempValue);\r\n}\r\n\r\nprivate PropertyMemento&lt;Control, AnchorStyles&gt; GetAnchorMemento(\r\n    Control control, AnchorStyles tempValue)\r\n{\r\n    return new PropertyMemento&lt;Control, AnchorStyles&gt;(\r\n        control, () =&gt; control.Anchor, tempValue);\r\n}<\/pre>\n<p>Notice that the logic of <code>SomeMethod()<\/code> is <strong>exactly the same<\/strong> 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 <code>using(){ }<\/code> statement. <code>GetAutoSizeMemento()<\/code> and <code>GetAnchorMemento()<\/code> are just two simple helper methods to create the Memento objects, which support readability in this blog post, but nothing more&#8230;<\/p>\n<p>So how is the Property Memento working <strong>conceptually<\/strong>? On creation of the Property Memento it stores the original value of an object&#8217;s property. Optionally it&#8217;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 <code>Dispose()<\/code> 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.<\/p>\n<p>The <strong>technical implementation<\/strong> of the Property Memento in C# uses Reflection and is shown below (<em>edit: find a better implementation <a href=\"http:\/\/www.minddriven.de\/index.php\/technology\/development\/design-patterns\/property-memento-followup\">here<\/a><\/em>):<\/p>\n<pre class=\"brush:csharp\">public class PropertyMemento&lt;TClass, TProperty&gt; : IDisposable\r\n    where TClass : class\r\n{\r\n    private readonly TProperty _originalPropertyValue;\r\n    private readonly TClass _classInstance;\r\n    private readonly Expression&lt;Func&lt;TProperty&gt;&gt; _propertySelector;\r\n\r\n    public PropertyMemento(TClass classInstance,\r\n        Expression&lt;Func&lt;TProperty&gt;&gt; propertySelector)\r\n    {\r\n        _classInstance = classInstance;\r\n        _propertySelector = propertySelector;\r\n      \u00a0 _originalPropertyValue =\r\n            ReflectionHelper.GetPropertyValue(classInstance, propertySelector);\r\n    }\r\n\r\n    public PropertyMemento(TClass memberObject,\r\n        Expression&lt;Func&lt;TProperty&gt;&gt; memberSelector, TProperty tempValue)\r\n        : this(memberObject, memberSelector)\r\n    {\r\n        SetPropertyValue(tempValue);\r\n    }\r\n\r\n    public void Dispose()\r\n    {\r\n        SetPropertyValue(_originalPropertyValue);\r\n    }\r\n\r\n    private void SetPropertyValue(TProperty value)\r\n    {\r\n        ReflectionHelper.SetPropertyValue(\r\n            _classInstance, _propertySelector, value);\r\n    }\r\n}<\/pre>\n<p>This implementation uses the following <code>ReflectionHelper<\/code> class:<\/p>\n<pre class=\"brush:csharp\">static class ReflectionHelper\r\n{\r\n    public static PropertyInfo GetProperty&lt;TEntity, TProperty&gt;(\r\n        Expression&lt;Func&lt;TProperty&gt;&gt; propertySelector)\r\n    {\r\n        return GetProperty&lt;TEntity&gt;(GetPropertyName(propertySelector));\r\n    }\r\n\r\n    public static PropertyInfo GetProperty&lt;T&gt;(string propertyName)\r\n    {\r\n        var propertyInfos = typeof(T).GetProperties();\r\n        return propertyInfos.First(pi =&gt; pi.Name == propertyName);\r\n    }\r\n\r\n    public static string GetPropertyName&lt;T&gt;(\r\n        Expression&lt;Func&lt;T&gt;&gt; propertySelector)\r\n    {\r\n        var memberExpression = propertySelector.Body as MemberExpression;\r\n        return memberExpression.Member.Name;\r\n    }\r\n\r\n    public static TProperty GetPropertyValue&lt;TEntity, TProperty&gt;(\r\n        TEntity entity, Expression&lt;Func&lt;TProperty&gt;&gt; propertySelector)\r\n    {\r\n        return (TProperty)GetProperty&lt;TEntity, TProperty&gt;(propertySelector)\r\n            .GetValue(entity, null);\r\n    }\r\n\r\n    public static void SetPropertyValue&lt;TEntity, TProperty&gt;(TEntity entity,\r\n        Expression&lt;Func&lt;TProperty&gt;&gt; propertySelector, TProperty value)\r\n    {\r\n        GetProperty&lt;TEntity, TProperty&gt;(propertySelector)\r\n            .SetValue(entity, value, null);\r\n    }\r\n}<\/pre>\n<p>As you can see, the Property Memento implementation is no rocket science. The constructor gets the class instance and an <code>Expression<\/code> 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 <code>ReflectionHelper<\/code> class. For the sake of shortness the implementation doesn&#8217;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.<\/p>\n<h3>Really a pattern and a Memento?<\/h3>\n<p>I&#8217;ve used the Property Memento now in several different situations with success and thus I think it&#8217;s justified to call it a <em>pattern<\/em>.<\/p>\n<p>But is it a <em>Memento<\/em> as well? Wikipedia says about the <a href=\"http:\/\/en.wikipedia.org\/wiki\/Memento_pattern\" target=\"_blank\">Memento pattern<\/a>:<\/p>\n<blockquote><p>&#8222;The <strong>memento pattern<\/strong> is a <a title=\"Design pattern (computer science)\" href=\"http:\/\/en.wikipedia.org\/wiki\/Design_pattern_%28computer_science%29\">software design pattern<\/a> that provides the ability to restore an object to its previous state [&#8230;]&#8220;<\/p><\/blockquote>\n<p>And this is true for the Property Memento, where the &#8222;object&#8220; equals a property value on a class instance! The &#8222;previous state&#8220; is stored on creation of the Memento and &#8222;restore an object&#8220; is done on call of <code>Dispose()<\/code>.<\/p>\n<h3>Finally<\/h3>\n<p>This blog post has shown the Property Memento as pattern for storing original property values and later on restoring them.<\/p>\n<p>Compared to the &#8222;manual way&#8220; the Property Memento has valuable advantages. It <strong>encapsulates the responsibility<\/strong> of storing an original value and restoring it when the <code>using()<\/code> block is finished. Client code remains clean and is condensed to the <strong>core logic<\/strong>, while delegating responsibilities to the Property Memento by an explicit <code>using(){ }<\/code> block. Thus the code becomes much more concise and <strong>readable<\/strong>. Last but not least the Property Memento employs an automatic <strong>exception handling<\/strong> mechanism. If an exception occurs inside a <code>using()<\/code> block of the Property Memento, finally the <code>Dispose()<\/code> method is called. Thus the Property Memento restores the original property state even in exceptional situations and the user gets a consistent layouted UI.<\/p>\n<p><a href=\"http:\/\/www.dotnetkicks.com\/kick\/?url=http%3a%2f%2fwww.minddriven.de%2f%3fp%3d975\"><img decoding=\"async\" src=\"http:\/\/www.dotnetkicks.com\/Services\/Images\/KickItImageGenerator.ashx?url=http%3a%2f%2fwww.minddriven.de%2f%3fp%3d975\" border=\"0\" alt=\"kick it on DotNetKicks.com\" \/><\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>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&#8217;s a common task in several scenarios: you want to store the &hellip; <a href=\"https:\/\/www.minddriven.de\/index.php\/technology\/development\/design-patterns\/property-memento-pattern\" class=\"more-link\"><span class=\"screen-reader-text\">The Property Memento pattern<\/span> weiterlesen<\/a><\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[12],"tags":[264,268,267,277,269,149],"class_list":["post-975","post","type-post","status-publish","format-standard","hentry","category-design-patterns","tag-design-pattern","tag-memento","tag-property","tag-property-memento","tag-restore-value","tag-state"],"_links":{"self":[{"href":"https:\/\/www.minddriven.de\/index.php\/wp-json\/wp\/v2\/posts\/975","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.minddriven.de\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.minddriven.de\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.minddriven.de\/index.php\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/www.minddriven.de\/index.php\/wp-json\/wp\/v2\/comments?post=975"}],"version-history":[{"count":19,"href":"https:\/\/www.minddriven.de\/index.php\/wp-json\/wp\/v2\/posts\/975\/revisions"}],"predecessor-version":[{"id":1063,"href":"https:\/\/www.minddriven.de\/index.php\/wp-json\/wp\/v2\/posts\/975\/revisions\/1063"}],"wp:attachment":[{"href":"https:\/\/www.minddriven.de\/index.php\/wp-json\/wp\/v2\/media?parent=975"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.minddriven.de\/index.php\/wp-json\/wp\/v2\/categories?post=975"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.minddriven.de\/index.php\/wp-json\/wp\/v2\/tags?post=975"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}