Wrap a collection that is a core part of your system in a meaningful helper class, and you'll soon find yourself adding helper methods to the new class.

A wrapped collection means the internal storage method is hidden away and the developer can control access to the internal collection.  Utility methods that are not normally provided by a collection can be added, such as findBySurname( ... ).  

Lack of direct client access to the collection means it can be secretly scaled up from a List to a Map without affecting calling code, something that might be done to allow faster searching of the collection.

In the following example, callers had to know to carefully synchronize changes to the underlaying Map and to cast values appropriately.  This was done in many places throughout the code.

:

Map rules = new HashMap();

:
// code to load rules file here again:
rules.put(rule1.getName(),rule1);
rules.put(rule2.getName(),rule2);
rules.put(rule3.getName(),rule3);
:
Rule myRule = (Rule)rules.get(“account”);
:

With so much repeated code, it was decided to move much of the logic into a RuleManager class.

:

// single threaded only
public class RuleManager
{
    private Map rules = new HashMap();

    public void loadRuleFile(File filename)
    {
        :
    }

    public void addRule(Rule rule)
    {
        rules.put(rule.getName(), rule);
    }

    public Iterator iterateRules()
    {
        return rules.values().iterator();
    }

    public Rule getRule(String name)
    {
        return (Rule)rules.get(name);
    }
}

So any calling code would be much more readable:

RuleManager rules = new RuleManager();
rules.loadRuleFile(filename);
Rule myRule = rules.getRule(“account”);

In the next example, the developer added a nested Map/String/List combination as the return value from the method.

public static Map<String, List<AbstractDisplayItem> > prepareVisibleDisplayItemsMap(
ServiceFacade serviceFacade,
ArticleMediaListTO article,  
int pageIndex)
{
    :
}

Whether you understand generics or not, the Map<String, List<AbstractDisplayItem>> hides the real return value, which is “rendering data” - generic information for rendering a screen correctly.

You could wrap the collection in a class.

public static RenderingData convertToRenderingData(
ServiceFacade serviceFacade,
ArticleMediaListTO article,  
int pageIndex)
{
    :
}

public class RenderingData
{
    private Map<String, List<AbstractDisplayItem> > displayItems;

    public List<AbstractDisplayItem> getDisplayItemsOfType(String displayType)
    {
        :
    }

    public boolean isBalancedArticle()
    {
    }
}

Once the collection was wrapped sufficiently, the developer was able to add an isBalancedArticle( ) method to describe the wrapped collection further.

blog comments powered by Disqus