Consider wrapping properties maps or lists in their own class

A common pattern in Java is to use a List, Map, Set, or other collection object when faced with keeping a variable number of properties about an object. Sometimes this is seen in obvious anti-patterns like holding URL parameters in a map. Other times there is a legitimate reason. For example, the book Head First OO Analysis and Design illustrates modeling an unknown number of guitar features for items in a guitar shop inventory with a map holding values like {fretboard = maple, tuners = locking}. The available information to be held in this map varies depending on what the manufacturer has provided about a particular item.

image

There’s nothing completely wrong about this latter example or approaches like it, but it can be better. The whole idea of OOP is to provide tools for semantically representing the real world in code. So consider using a class that wraps your collection and provides methods specific to the context. For instance, in the guitar example, you could make a GuitarFeatures class with method add(String guitarPart, String description). The simple ability to have variable names in this method signature that really make sense to what we’re doing aids in readability and maintainability. It is easily better than simply having a map with “keys” and “values.”

image

Still more can be achieved with an OO approach. You can include validation of inputs inside such a method. You can choose a different name than “add” or “put” in order to move away from revealing that the implementation is a list or map. You can gain maintainability by encapsulating the collection within the class as a private field, so that if the application’s needs change in the future, you can change the data structure altogether, with no need at all for updating all the code where it’s used. Such a scenario arises when one day a simple key->value map may not be enough for good performance, and lookup by a second key is desired. Then you might simply change the internal structure to a multi-key map such as (key1 | key2)->value.

In short, we can do far better than simply reaching for a sensible data structure, by leveraging the power of OOP! Wrapping a collection in a semantically sensible class that models our problem space eases readability. Using encapsulation improves maintainability. The application code becomes much, much better.

Leave a Reply

Your email address will not be published. Required fields are marked *