java - errors/exceptions accumulating design pattern -
a method returns result, making number of "attempts" build it. first attempt succeeds should return. if none of them succeed exception should thrown:
class calculator { public string calculate() throws exception { // how design it? } private string attempt1() throws exception { // try calculate , throw if fails } private string attempt2() throws exception { // try calculate , throw if fails } private string attempt3() throws exception { // try calculate , throw if fails } }
it's important mention exception thrown calculate
should preserve stack traces of other exceptions thrown private methods. how recommend design calculate()
method, extendability , maintainability in mind?
i use composite , command.
interface calculatecommand { public void calculate(calculatecontext context); }
now create implementation each attempt want.
next create compositecommand -- here outline (you need fill in blanks)
public class compositecalculatecommand implements calculatecommand { compositecalculatecommand(list<compositecommand> commands) { this.commands = commands; // define field } public void calculate(commandcontext context) { (calculatecommand command : commands) { try { command.calculate(context); } catch(runtimeexception e) { this.exceptions.add(e) // initialize list hold exceptions } if (context.hasresult) return; // break } // throw here. didn't success since never saw success in context. have list of exceptions. } }
finally use like
calculatecommand allcommands = new compositecalculatecommand(somelistofcommands); allcommands.calculate(somecontextthatyoudefine); // results on context.
note each command implementation testable on own, maintainable. if need add calculations, define new type of calculatecommand
, extensible. play dependency injection. note define commandcontext object different commands can take different types of stuff (put in context).