Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 893
The Unfun Cat Avatar asked Jan 15 '23 19:01

The Unfun Cat


2 Answers

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.

like image 112
Tomasz Nurkiewicz Avatar answered Mar 13 '23 07:03

Tomasz Nurkiewicz


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.

like image 36
Razvan Avatar answered Mar 13 '23 05:03

Razvan