Reputation: 15341
I have a simple (and possibly quite common) design issue. Let's say I have an interface that looks like this:
public interface AnalysisResult {
BigDecimal getMeasure();
}
This, However, is later implemented by several different concrete implementations - some including average field as well, some containing counts of various properties etc. Now, I am given a set of AnalysisResult
and I would like to be able to output the results according to the type, i.e. Mean result would say what the mean is on top of the Measure etc. One way to do this would be to expose a method on the interface say outputResult()
, but the problem is I might want to output the result in the HTML format, CSV and many others, so I would require a method for each. Also, there might be the case I want to output something based on the type, such as : 'This is the Mean result'... Would you say that in this case it would be easier to simply use instanceof
and do the work on the outputter side?
Upvotes: 1
Views: 800
Reputation: 1489
Save result data in a common xml format and use XSLT to transform raw data to your desired format. JUnit does this with test results. No code change needed when you later on decide to add a different format.
Upvotes: 0
Reputation: 3274
I suggest to use a method public String getOutput(String format) in the interface.
Let the implementations decide what to return based on the 'format' argument.
This will also help to call method specific to a particular implementation.
Upvotes: 0
Reputation: 10667
results according to the type :
This is a separate behavior so would suggest you to implement something like Strategy Pattern. Have a base interface having method print(). Then you can implement this method in multiple Implementing classes like CSVStylePrint, HTMLStylePrint etc.
This way your printing functionality is separate and you follow OCP (Open Closed principle : i.e. Open for extension but closed for changes) principle. OCP is the underlying design principle used in Strategy Pattern.
Upvotes: 0
Reputation: 6873
I'd go for a further extension.. something like
public interface Measure {
public String getOutputAsTxt();
public String getOutputAsCsv();
public String getOutputAsFunnyFormat();
};
public interface AnalysisResult {
public Measure getMeasure();
}
Thus moving the output specialization to the particular Measure. Yes this add a bit of code but keeps everything neat and separated.
Or I'd try to explore a bit the Visitor pattern (this is a sort of simple implementation).
For further information, please refer to the chosen answer in this SO question (every time I read it I feel the urge to +1 for its awesomess)
Upvotes: 1