advertisement

Print

What Is Prefactoring
Pages: 1, 2, 3

Extreme Separation

The guideline "If It Has Collection Functionality, Make It a Collection" advises that a field or attribute that represents an aggregation, such as an array, should be separated in its own class. For example, suppose you had an attribute and a method as:



    class Customer
        {
        Dollar purchases[]; 
        // . other attributes and methods
        Dollar average_purchases(); 
        }

In average_purchases(), you create a loop or use an iterator, or employ a language-dependent mechanism. That places code inside of Customer that is concerned with manipulating only Dollars. Instead, you could make the Dollar array into a collection, as:

    class DollarCollection
        {
        // "Collection Functionality" 
        Dollar average() {}
        Dollar smallest() {}
        Dollar largest() {}
        Dollar total() {} 
        // Plus standard collection methods, such as 
        addDollar(Dollar aDollar){}
        //. 
        }

Now the class looks like:

    class Customer
        {
        DollarCollection purchases;
        }

And the code to determine the average is simply:

    Dollar average_purchases()
        {
        return purchases.average();  
        }

Inside of DollarCollection, you can use whatever mechanism you want to hold the elements of the collection -- an array, a Vector, or even a database table. This separation of implementation from use makes the code easier to maintain.

Pages: 1, 2, 3

Next Pagearrow