Keeping data and formatting separate in object oriented design

java, object-oriented-analysis

Solution

The worst thing you can do is coupling your hierarchy data representation with formatting. The hierarchy class should not know anything about formatting. My advice is to create a separate interface `HierarchyFormatter` with several different implementations.

I think code is worth thousand words:

public interface HierarchyFormatter {
    String format(Hierarchy hierarchy);
}

public class BraceFormatter implements HierarchyFormatter {
    public String format(Hierarchy hierarchy) {
        //...
    }
}

public class RangeFormatter implements HierarchyFormatter {
    public String format(Hierarchy hierarchy) {
        //...
    }
}

This is called a strategy design pattern. If some code needs to format your hierarchy, just pass an instance of `HierarchyFormatter` - any instance.

If you want to permanently bind hierarchy with some formatting, make your formatter stateful:

public abstract class HierarchyFormatter {
    protected final Hierarchy hierarchy;

    public HierarchyFormatter(Hierarchy hierarchy) {
        this.hierarchy = hierarchy;
    }

    public abstract String format();
}

public class BraceFormatter extends HierarchyFormatter {
    public String format() {
        //...
    }
}

public class RangeFormatter extends HierarchyFormatter {
    public String format() {
        //...
    }
}

Every time you create a formatter, you encapsulate the hierarchy class inside it.

Problem

I am creating a program where I have objects called "hierarchies", which is little more than a list of lists with strings (`ArrayList<ArrayList<String>>`) with appropriate getters. The user should be able to select the representation/formatting of these hierarchies - e.g. whether the hierarchy [1,2,3,4] should be represented as {1,2,3,4} or (1-4) or whatever, before it is written to a file. Is there a clever/standard way to do this kind of separation of data and formatting? I am thinking of creating a "FormattedHierarchy"-object which merely consists of a Hierarchy-object and a Formatting-object, but I don't know if this is a good design choice or not. Thanks for any pointers/tips/answers.

Original source