Returning a value to caller via chain of methods

Say I call a method. I want a return value from that method. However, this method delegates tasks to other methods, which in turn may delegate tasks to other methods still. The value that gets eventually returned by the top most method is ultimately determined by the submethods, and the submethods' submethods.

Imagine this scenario:

 public String method1(Object o){

if(x)
return subMethod1(o);
if(y)
return subMethod2(o);
if(z)
return subMethod3(o);
else
return "";

}

//example submethod

public String subMethod1(Object o){

if(a)
return subSubMethod1(o);
if(b)
return subSubMethod2(o);
if(c)
return subSubMethod3(o);
else
return "";

}

//example subsubmethod

public String subSubMethod1(Object o){

//etc etc

return "";

}

This a reoccurring problem for me, and I am hoping there is a design pattern to solve this type of problem.

Is there such a design pattern?

Jon Skeet
people
quotationmark

The conditional operator makes each set of choices simple - and if you lay it out correctly, it's really easy to read, once you've got the hang of the pattern:

return x ? subMethod1(o)
     : y ? subMethod2(o)
     : z ? subMethod3(o)
     : "";

Of course, if your decisions could actually be laid out along polymorphic lines (i.e. the conditions map to which type the object is at execution time) then you can use inheritance to solve this instead. But if you really do just need multiple conditions like this, the conditional operator can be very helpful.

people

See more on this question at Stackoverflow