Information Expert GRASP Pattern Take 2

I have been talking about the Information Expert GRASP Pattern as it pertains to my Create a Shopping Cart example.

I have been fixing the original code to remove code smells as well as make sure the Information Expert Principle is being followed.  In this example, I am changing the following code as follows:

 

ShoppingCart Class
public class ArrayListCart : ShoppingCart
{
    private ArrayList _items;
    
    // ...
    
    public override void AddItem(Item item)
    {
        int index = _items.IndexOf(item);

        if (index >= 0)
            UpdateItem(item);
        else
            _items.Add(new Item(item.ProductID,
item.ProductName, item.Quantity, item.UnitPrice)); }
// ... }

 

In the AddItem method above, the ArrayListCart class "makes a copy" of item before placing it in the _items ArrayList.  As I mentioned in the Creat a Shopping Cart post, this is not ideal (bogus actually) as ArrayListCart is not the Information Expert on what it takes to make a copy of ItemItem is.  Item should have a Copy() method to make a copy of itself.

 

ShoppingCart Class
public class ArrayListCart : ShoppingCart
{
    private ArrayList _items;
    
    // ...
    
    public override void AddItem(Item item)
    {
        int index = _items.IndexOf(item);

        if (index >= 0)
            UpdateItem(item);
        else
            _items.Add(item.Copy());
    }
    
    // ...
    
}

 

Item's Copy Method
public Item Copy()
{
   return new Item(this._productID, this._productName,
        this._quantity, this._unitPrice);
}

 

Now we have a much cleaner solution that follows the Information Expert GRASP Pattern.  Although you don't have to follow these principles as if they are written in stone, you can see that they may help show problems in your code.  Check out Applying UML and Patterns for more information on GRASP Patterns.

posted on Monday, March 28, 2005 10:13 PM

Main

News

Green Tea

.NET Development

Enterprise Library

Patterns & Practices