Search code examples
exceptionlanguage-agnosticcontrol-flow

Is it possible to make this pattern more DRY?


I've run into this a few times:

try {
  if (condition()) {
    return simpleFunction(with, some, args);
  } else {
    return complexFunction(with, other, args);
  }
catch (something) {
  // Exception thrown from condition()
  return complexFunction(with, other, args);
}

Is there any way (in any language) to avoid repeating the call to complexFunction? Ideally without obscuring the intent of the code?


Solution

  • if c#, you could do...

        try
        {
            if (condition()) {
                return simpleFunction(with, some, args);
            }
        }
        catch
        {
            // Swallow and move on to complex function
        }
    
        return complexFunction(with, other, args);
    

    Updated to have condition exception continue up the stack

    if (condition()) {
        try
        {
            return simpleFunction(with, some, args);
        }
        catch
        {
            // Swallow and move on to complex function
        }
    }
    return complexFunction(with, other, args);