The Unfun Cat
The Unfun Cat

Reputation: 31908

Keeping data and formatting separate in object oriented design

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.

Upvotes: 4

Views: 1043

Answers (3)

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340733

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.

Upvotes: 6

Razvan
Razvan

Reputation: 10093

You can approach it as a Model-View pattern. Your model is the one containing the actual data: ArrayList<ArrayList<String>> and the view is the one doing the formatting, presenting the data in various ways. and that is the Formatting class.

Upvotes: 2

Ridcully
Ridcully

Reputation: 23655

You could add methods similar to the standard toString() methods, e.g. toArrayString() to format the object as {1,2,3,4} or toIntervalString() to format it as (1-4) ...

Upvotes: 1

Related Questions