Memento Design Pattern

In this post I’ll explore the Memento Design Pattern which is a Behavioural pattern. If this is the first time you are coming to this site, you can also checkout my earlier posts related to Design Patterns And Enterprise Patterns. Gang of Four defines Memento pattern as a way to capture the internal state of an object without violating the encapsulation. It allows us to restore the state at a later point of time.

Problem statement

Assume we are building shopping cart software for a retailer. The user has an option to persist the shopping cart and amend it on subsequent visits to the website of the retailer. Until the user checks out the order and makes the payment, he or she is allowed to amend the order unlimited times. During modification user can also decide not to persist his changes in which case any unsaved changes should be reverted and the order state should be set to the last persisted state.

Shopping Cart without Memento

We start with a very basic ShoppingCart class which consists of different methods for manipulating the cart items collection.

    public class ShoppingCart

    {

        private IList<CartItem> currentCartItems;

 

        public ShoppingCart()

        {

            CartItems = new List<CartItem>

                {

                    new CartItem { Id = 1, ProductName = "Lays Chips", Quantity = 2, UnitPrice = 5 },

                    new CartItem { Id = 2, ProductName = "Coca Cola", Quantity = 1, UnitPrice = 15 }

                };

        }

 

        public int Id { get; set; }

 

        public IList<CartItem> CartItems { get; set; }

 

        public void AddItem(CartItem cartItem)

        {

            CartItems.Add(cartItem);

        }

 

        public void RemoveItem(CartItem cartItem)

        {

            CartItems.Remove(cartItem);

        }

 

        public void EditCart()

        {

            currentCartItems = new List<CartItem>(CartItems);

        }

 

        public void CancelEditing()

        {

            CartItems = new List<CartItem>(currentCartItems);

        }

 

        public void SaveCart()

        {

            // persist changes to database

        }

    }

In the above code snippet the constructor initializes the CartItems collection with two items. This kind of simulates the fetching of existing items from the persisted database. Assume that there is some service which takes care of populating these CartItem objects with the values from the persistent medium.

The ShoppingCart class exposes following methods to manipulate the contents of the cart.

  • AddItem adds new CartItem to the items collection
  • RemoveItem removes existing item from the collection
  • EditCart method is used to change the state of cart from read only mode to update mode
  • CancelEditing method is used to cancel the changes which are not yet saved into the database
  • SaveCart is used to persist the changes to the database.

The workflow is as follows, user chooses to put the Cart into Edit mode by invoking the EditCart method. At this point a copy of the existing items are saved into a variable currentCartItems. The user can modify the cart items by adding or removing the items. The changes can be persisted by invoking SaveCart method or cancel edits by invoking the CancelEdit method.

            ShoppingCart shoppingCart = new ShoppingCart();

 

            Console.WriteLine("Print initial state");

            PrintCartDetails(shoppingCart.CartItems);

 

            shoppingCart.EditCart();

 

            shoppingCart.AddItem(new CartItem { Id = 3, ProductName = "Pepsi", Quantity = 1, UnitPrice = 2 });

 

            Console.WriteLine("Print after adding 1 cart item");

            PrintCartDetails(shoppingCart.CartItems);

 

            shoppingCart.CancelEditing();

 

            Console.WriteLine("Print after cancelling edit");

            PrintCartDetails(shoppingCart.CartItems);

In the above code snippet, we added a new item to the shopping cart and cancelled the change. Since persisting changes to database are outside the scope of this post, I’ll not touch upon that topic here.

The ShoppingCart class gets the job done as per the requirement. This would be sufficient in most cases. Do you see any flaw with this approach? Although not a major flaw but this method does pose a problem because the state is stored within the same class which can be restored later. Since the data is available to class methods, it might be possible for some other method to change the state unintentionally. How can we avoid such unintentional modification to the internal state of the object?

The Memento Design Pattern comes handy in the situation explained above. We can externalize the storage of CartItems instead of storing them in the currentCartItems variables. At the points where we wish to restore the collection, we restore it from the external source. By providing read-only access to the state of the external object we can avoid tempering with the intermediate state.

Refactoring towards Memento Pattern

We start off with defining a class which will store the data that we are interested in. This happens to be the cart items collection. We define the CartItemsMemento class as shown below

    public class CartItemsMemento

    {

        private readonly IList<CartItem> _cartItems;

 

        public CartItemsMemento(IList<CartItem> cartItems)

        {

            _cartItems = new List<CartItem>(cartItems);

        }

 

        public IList<CartItem> CartItems

        {

            get

            {

                return _cartItems;

            }

        }

    }

The only responsibility for this class is to hold onto the state of an object which can be restored later. Next step is to get this data structure out of the ShoppingCart class. Here is the refactored ShoppingCart implementation.

    public class ShoppingCart

    {

        public ShoppingCart()

        {

            CartItems = new List<CartItem>

                {

                    new CartItem { Id = 1, ProductName = "Lays Chips", Quantity = 2, UnitPrice = 5 },

                    new CartItem { Id = 2, ProductName = "Coca Cola", Quantity = 1, UnitPrice = 15 }

                };

        }

 

        public int Id { get; set; }

 

        public IList<CartItem> CartItems { get; set; }

 

        public void AddItem(CartItem cartItem)

        {

            CartItems.Add(cartItem);

        }

 

        public void RemoveItem(CartItem cartItem)

        {

            CartItems.Remove(cartItem);

        }

 

        public void EditCart()

        {

            // changes state from readonly to edit mode

        }

 

        public void CancelEditing()

        {

            // reverts back to readonly mode

        }

 

        public CartItemsMemento CreateMemento()

        {

            return new CartItemsMemento(CartItems);

        }

 

        public void RestoreCartItems(CartItemsMemento memento)

        {

            CartItems = new List<CartItem>(memento.CartItems);

        }

 

        public void SaveCart()

        {

            // persist changes to database

        }

    }

We have got rid of the currentCartItems private variable. Instead we have added two method CreateMemento and RestoreCartItems. CreateMemento returns a new instance of CartItemsMemento with the current shopping cart items. The restore method is used to restore the state stored inside the memento object.

By doing these changes we have the source of the object and the destination where it needs to reside temporarily. How do we glue them together. To bring the pieces together we have another intermediate class which acts as the caretaker of this data. I named it as CartItemsCareTaker.

    public class CartItemsCareTaker

    {

        public CartItemsMemento CartItemsMemento { get; set; }

    }

The only job of this class is to temporarily hold onto the internal state stored inside of the memento object. We are almost done with these changes. Here is the client code which makes use of these classes.

            ShoppingCart shoppingCart = new ShoppingCart();

 

            Console.WriteLine("Print initial state");

            PrintCartDetails(shoppingCart.CartItems);

 

            CartItemsCareTaker careTaker = new CartItemsCareTaker { CartItemsMemento = shoppingCart.CreateMemento() };

 

            shoppingCart.AddItem(new CartItem { Id = 3, ProductName = "Pepsi", Quantity = 1, UnitPrice = 2 });

 

            Console.WriteLine("Print after adding 1 cart item");

            PrintCartDetails(shoppingCart.CartItems);

 

            shoppingCart.RestoreCartItems(careTaker.CartItemsMemento);

 

            Console.WriteLine("Print after cancelling edit");

            PrintCartDetails(shoppingCart.CartItems);

Note that we invoke the shoppingCart.CreateMemento and shoppingCart.RestoreCartItems methods here.

Conclusion

Although using Memento pattern increases the number of classes in the solution, it increases the maintainability by splitting the responsibilities between the Originator (ShoppingCart), the Care taker (CartItemsCareTaker) and Memento (CartItemsMemento) classes. Each class has a unique responsibility. We achieve the objective of separating the internal state of an object using an encapsulated manner with the help of the care taker class. Anytime there is a need to backup and restore the internal state of object we should consider using the Memento pattern instead of managing the state within the same class.

The complete working solution is available for download Memento Design  Pattern Demo.zip

Until Next time Happy Programming.

Further Reading

Based on the topics discussed in this post I would like to recommend following books.

spacer

Distributed Version Control System

Over the past decade or so there has been an exponential rise in the usage of Distributed Version Control System (DVCS). This post is about my experiences in using GitHub and Bitbucket distributed version control systems. I would like to share my experience in setting up the systems on a Windows 7 PC.

GitHub & BitBucket

There is already so much information available on the history and evolution of Version Control Systems that I would not like to repeat it myself. There has been lot of talk off late about the Distributed version control systems. Initially these DVCS were considered to be mostly suitable for Open Source projects. Recently I was part of a group discussion where one of the member suggested using DVCS in an enterprise application. The advantage offered by DVCS was the ease of merging and better support for branching. Although we did not progress much on that discussion, it was worth noting that there are other enterprises who are using this approach and leveraging the benefits offered by DVCS systems.

I was looking for some means of storing the source code I use for my blog entries in the file sharing systems over the internet. I have been using Dropbox for long time. The problem with Dropbox is that it is a file sharing system and not a source control repository. Apart from the blog source codes, I also have some personal projects which I keep updating with the changes in technology. This is where I found GitHub useful for storing the source codes.

GitHub

GitHub is built on top of Git and offers various pricing options. It is free for open source projects. You can store your code as open source in GitHub repositories. GitHub promotes itself as social coding website. There are various GUI based clients for Git on Windows. Here is a link which gives a step by step guide to setting up GitHub and in turn Git on a Windows PC.

There are different ways of working with a DVCS on your PC. If you are a geek and like to work off the command line, you can work with GitHub using the shell. Unfortunately I am not a command line freak and prefer to have a GUI to work with GitHub. There are multiple options available. I have tried the Msysgit Git GUI and TortoiseGit. Msysgit comes bundeled with the Git installation package. TortoiseGit is a port of TortoiseSVN for Git.

Setting up GitHub can take up some time. After installing the software you need to set up the RSA keys. If you are unable to set up the keys correctly you’ll not be able to store anything in GitHub. Once the Git software is installed on the PC we are ready to create Repository and push the changes to GitHub. These are the steps I undertake to setup new repository in GitHub. I’ll skip the steps related to registration with GitHub as it is one time activity. Assuming you are a registered GitHub user these are the steps to follow.

1 – Create a new Repo in GitHub

Git Homepage

We can create a new Repository in GitHub using any one of the highlighted options in the above screenshot. You can use the Create a Repository link under the Bootcamp section as indicated by 1 or the link under Welcome to GitHub indicated by 2 below the bootcamp section. There is also a New repository button next to Your Repositories. This is indicated by 3 or using the Create new repo button at the top right of the page as shown using 4. Except the first link all other redirect us to the repository creation page as shown below

Create Repository Screen

I want to add one of the directory containing source code available on my hard disk to GitHub. I created a repository named DecoratorDesignPattern

decorator repo on GitHub

Note the three highlighted areas in the above screenshot. At the top of the page we have the URL to the newly created repository. We can use one of the options from 2 or 3. If we are starting from scratch we can use the create new Repo on Command line option. If we have created the repository on the local hard drive we can use the third option that of pushing an existing repository from command line.

2 – Create new repository on command line

I need to set up a local copy of the remote repository. So I’ll use the Create a new repository from command line option. In Windows Explorer navigate to the directory where you wish to create the new repository and right click on the folder.

image

From the context menu select Git Bash Here option. It opens up the Git command prompt. Type the commands as shown in the previous screen

image

Please note that the GitHub url is case sensitive. After the repository is created, we can push the changes to the remote server. If everything goes fine you should be able to see a screen as below

image

With this step we have successfully pushed the contents of the local folder to a remote repository. If you don’t want to use the command line tools, you can use the GUI tools. Here is a screenshot of the default GUI provided by Git.

Git Gui Context Menu

Right click on the directory in Windows Explorer which contains the Git repository and select Git GUI Here option from the context menu. You’ll be able to perform all the operation that we performed using command line from the GUI as well.

Git GUI

The Git GUI is good option to start with. There are other client softwares which allows us to work with Git using GUI. I have also used Tortoise Git. This client offers much more options in the context menu as shown in the screen shot below

tortoise Git GUI

One of the major limitation of GitHub is that all your repositories will be public if you don’t want to subscribe to their monthly or yearly plans. As always now a days there are alternatives available and at times you are spoiled for the choices. Recently BitBucket started a service similar to GitHub with DVCS support.

BitBucket

It has support for multiple DVCS systems including Git and Mercurial. There is also an option of importing existing repositories from other providers like GitHub. The advantage it has over Git is that you can have unlimited number of private repositories. The process of setting up the system is also simpler compared to GitHub. You can follow the steps in this post to set up Bitbucket repository with either Git or Mercurial as DVCS. If you choose Mercurial as the option the download comes with a full featured Tortoise Hg GUI.

The steps for setting up a Mercurial repository and storing it remotely are relatively simple compared to Git. The link related to setting up of Bitbucket talks about creating new repository so I would not like to repeat it again. Following is the screenshot of the Tortoise Hg client for BitBucket

Tortoise Hg client

We can use the dashboard in the Bitbucket web site to create new repositories or import existing repositories from other sources like GitHub

BitBucket dashboard

Currently there are multiple sources supported by BitBucket to import your existing code as shown below

Bitbucket Import repo

Current support is provided for CodePlex, git/GitHub, Google Code, Mercurial, SourceForge and Subversion repositories. You can choose either Git or Mercurial as the target type and also make it a private repository.

Conclusion

Not everybody can afford to invest in a full fledged source control system. If you are in a small start-up or a individual freelancer, using these systems can help you to leverage the facilities of commercial SCM. As for me I use multiple laptops and copying files across multiple devices can be avoided using online storage. It also helps me maintain the history of changes even for a personal projects using lightweight version control system. I can now keep copies of all my trial projects in a central repository. Apart from the source code related to my blog posts, I can also store my personal projects as private repositories using BitBucket.

With DVCS you have a local copy of the repository. The speed is an advantage. These are designed for speed. After the repository is cloned from the central server, we do not need connection to central server. Operations like comparisons and version history can be done without network connectivity.

Until next time Happy Programming.

Further Reading

Based on the topics discussed in this post I would like to recommend following books as further reference.

spacer

Composite Design Pattern

In this post I’ll demonstrate the Composite Design Pattern. This is the next post in the Design Pattern Series which falls under the category of Structural Design Patterns. In the previous post we looked at the Builder Design Pattern which is used to build a complex or a composite object using a series of steps. Composite Design Pattern is very helpful when we have a tree structure and there is a need to treat the parent as well as child object in the same manner.

Problem Statement

Assume we are building software for a renowned retailer. The retailer has stores across the country. We need to calculate the profit for each City where the retailer operates. Also the profits need to be calculated at the State level. We can extend this example further by saying that various states can be grouped together into regions and so forth. For simplicity we will stop at the State level.

Profit Calculator Without Composite Pattern

Lets start with defining the domain objects related to this problem statement. We can map the requirement to different classes like Store, City and State. City class will contain a list of Stores within that city. Similarly State class will contain a list of States. We start with the simplest class Store.

    public class Store

    {

        public int Id { get; set; }

 

        public string Name { get; set; }

 

        public int Profit { get; set; }

    }

The Store class defined above is very simple and self explanatory. To keep things simple, we assume that the Profit at Store level is computed using some complex financial calculations which are outside the scope of this post. We don’t bother about how it is calculated, but we know that we’ll be able to calculate this value by some means. Lets move on to the City class which has a collection of Stores.

    public class City

    {

        public City()

        {

            CityStores = new List<Store>();

        }

 

        public int Id { get; set; }

 

        public string Name { get; set; }

 

        public IList<Store> CityStores { get; private set; }

 

        public void AddStore(Store store)

        {

            CityStores.Add(store);

        }

 

        public void RemoveStore(Store store)

        {

            CityStores.Remove(store);

        }

 

        public int GetCityProfit()

        {

            int profit = 0;

 

            foreach (Store store in CityStores)

            {

                profit += store.Profit;

            }

 

            return profit;

        }

    }

We have a CityStores collection which is manipulated using the AddStore and RemoveStore methods. We also have the GetCityProfit method which iterates all the stores and adds up the profits for them. Similarly we have the State class which is almost the same but operates at the City level while aggregating the profits.

    public class State

    {

        public State()

        {

            Cities = new List<City>();

        }

 

        public int Id { get; set; }

 

        public string Name { get; set; }

 

        public IList<City> Cities { get; private set; }

 

        public void AddCity(City city)

        {

            Cities.Add(city);

        }

 

        public void RemoveCity(City city)

        {

            Cities.Remove(city);

        }

 

        public int GetStateProfit()

        {

            int profit = 0;

 

            foreach (City city in Cities)

            {

                foreach (Store store in city.CityStores)

                {

                    profit += store.Profit;

                }

            }

 

            return profit;

        }

    }

AddCity and RemoveCity methods help in managing the list of Cities related to a particular State. The GetStateProfit method iterates over two collections. The first iteration is for the cities within the state and the next loop is for all the stores within a city.

Limitations of this approach

As we can see from the above code for every level of hierarchy we have additional looping to do in order to compute the profit. For example imagine what will happen if we were to calculate the profit at the regional level by combining multiple states together. In another scenario imagine if we have a big metropolitan city which we wish to split further into smaller groups.

There exists a hierarchy between a top level element and its children like State and City and also City and individual Store elements. All that we are doing is performing similar operation be it at the parent level or the child level. All this process could be simplified if we can treat the parent which contains a list of child objects and the child nodes itself in the same manner. This is exactly the kind of situation tailor made for implementing the composite design pattern.

Refactoring towards Composite Pattern

The crux of the composite pattern is that we can treat the composite object and the individual leaf object in exactly the same way. In order to do that we can define an interface which can be implemented by both the parent and the child nodes.

    public interface IProfitable

    {

        int GetProfit();

 

        void AddChild(IProfitable child);

 

        void RemoveChild(IProfitable child);

    }

The IProfitable interface defines a method for getting the profit and to manage the child elements. All the interested objects will implement this interface. This interface definition seems ok for those objects which have child elements associated with them like State or City. The problem comes if we were to implement the same interface at the leaf node level which happens to be Store in our context. Lets see the Store class implementation.

    public class Store : IProfitable

    {

        public int Profit { get; set; }

 

        public int GetProfit()

        {

            return Profit;

        }

 

        public void AddChild(IProfitable city)

        {

            throw new NotImplementedException();

        }

 

        public void RemoveChild(IProfitable city)

        {

            throw new NotImplementedException();

        }

    }

We implement only the methods of IProfitable which are relevant at the leaf level like GetProfit in this case. GetProfit simply returns the value of Profit property. The methods related to child management AddChild and RemoveChild are not implemented and throw exception if the client tries to invoke these methods. Lets continue to the City class implementation.

    public class City : IProfitable

    {

        public City()

        {

            Stores = new List<IProfitable>();

        }

 

        public IList<IProfitable> Stores { get; private set; }

 

        public int GetProfit()

        {

            int profit = 0;

 

            foreach (IProfitable store in Stores)

            {

                profit += store.GetProfit();

            }

 

            return profit;

        }

 

        public void AddChild(IProfitable store)

        {

            if (store is Store)

            {

                Stores.Add(store);

            }

        }

 

        public void RemoveChild(IProfitable store)

        {

            Stores.Remove(store);

        }

    }

In case of City class the code is mostly the same as it was previously with the exception that we are referring the list as well as the parameters to the AddChild and RemoveChild methods using the IProfitable interface. Because of this we have to add the type cheking logic in the AddChild and RemoveChild methods to make sure the type of parameter which is passed is Store. Now lets look at the refactored Sate class

    public class State : IProfitable

    {

        public State()

        {

            Cities = new List<IProfitable>();

        }

 

        public IList<IProfitable> Cities { get; private set; }

 

        public int GetProfit()

        {

            int profit = 0;

 

            foreach (IProfitable city in Cities)

            {

                profit += city.GetProfit();

            }

 

            return profit;

        }

 

        public void AddChild(IProfitable city)

        {

            if (city is City)

            {

                Cities.Add(city);

            }

        }

 

        public void RemoveChild(IProfitable city)

        {

            Cities.Remove(city);

        }

    }

The State class is almost identical to City class. The difference comes in the implementation of the GetProfit method. We are no longer looping multiple times. We have only one level of looping which iterates over the child elements calling their respective GetProfit method. You can imagine how simple it would be to accommodate the two scenarios described above that of having regional profit within metropolitan city of profit at the regional level comprising multiple states. Also note that we no longer have methods like GetStateProfit or GetStateProfit. I agree that this discrepancy in names could have been solved in earlier implementation as well by using the same name GetProfit for all the classes.

Conclusion

Composite design pattern helps us to treat the composite and individual objects in the unified manner. It is used in situations where the part-whole hierarchies are used in code structure resulting in tree structure.

Many people prefer not to add the AddChild and RemoveChild or similar methods related only to the composite object to the interface. If we take this approach there is no need to throw exceptions from the leaf node class like we did for Store class. The composites can inherit from an abstract class which has the methods specific to composite objects.

As always the complete source code is available for download Composite Design Pattern Demo.zip.

Until next time Happy Programming.

Further Reading

Here are some books I recommend based on the topic discussed in this blog.

spacer