1

I come from a Java background, and my colleague is from .NET. We are working on a Java project and I saw him create a method like this:

public Object myMethod(Object[] param1, ErrorMessage errorMessage) {...}

ErrorMessage is a self-defined object that just holds a String, and is checked if empty or not in the caller.

I have encountered this years ago, and am quite surprised to see it again now. I am more partial to just throwing a RuntimeException, but then again isn't the try-catch clause just doing the same thing as if(!errorMessage.isEmpty())?

Is it an anti-pattern? What is it called? I feel that I am ill-equipped to argue my point, and so the code just sits there, haunting me.

2
  • Looks more like your colleague has a C background, where there are no exceptions. What did he answer when you asked him why he did not use an exception?
    – Doc Brown
    Commented Oct 11, 2018 at 20:58
  • ... and don't be astonished when you find some strange code during a review, even if the code in general looks good
    – Doc Brown
    Commented Oct 11, 2018 at 21:02

2 Answers 2

1

The only use I can think of for a pattern like this is if myMethod contains some boilerplate code that does an operation with param1, and then requires an errorMessage if the operation fails.

Having it contained in a method will DRY up the boilerplate code, so the callers of myMethod just need to specify param1 & errorMessage instead of repeating the boilerplate.

However, that doesn't seem to be the case you described. Checking if the errorMessage isn't empty & then handling the error sounds to me like a try/catch would be more suitable.

1

Coming from a Java background myself, I understand your confusion. However this can be perfectly valid if the error message coming in is part of what the method does.

In that I mean, if you were to say, process a response from an http call, this might be a perfectly legitimate way of handling a response to the caller. In case of error, respond with code 401, otherwise 200, for instance.

The error passed to the method in this case is purely a parameter like any other.

I would be more concerned about your colleague's preference to represent an error as ErrorMessage. If the possibility of an error is genuinely exceptional it should be an exception, and not an instance of an error message. Again, this also may be correct if there is a strong possibility of there being an error (not exceptional).

In conclusion, it seems if there is something wrong here, it is preference to not use exceptions to handle errors. Exceptions are expensive, of course, but so long as you're not using exceptions as a means to pass messages around in your program, they are perfectly valid and should be used in such cases.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.