1

This is somewhat of a design question. I am using the decorator pattern to handle cross-cutting concerns. One of these concerns is validation. Most of the examples I have seen do something like:

IAccount account = new AccountValidator(new Account());
account.Deposit();

and the implementation of the validator is something like:

if (!IsValid)
    throw new NotValidException();

overly simplistic, but hopefully you get the idea.

I had the impression this was bad practice (I could be wrong, that's the heart of my question really - is this bad practice?) The case isn't really an exception. It is a fairly typical and understandable user input error.

However, the only way I know how to avoid this kind of situation is to engineer all my service methods to return some kind of standardized object containing response data. So for example account.Deposit() returns an IResponse which is implemented by a number of possible classes, such as NotValidResponse : IResponse...

Thoughts?

Price Jones
  • 1,948
  • 1
  • 24
  • 40

1 Answers1

1

Exceptions should not be used to control the flow of data; they should be used for exceptional circumstances. I'd recommend returning some kind of Result object as you described, or a bool, or otherwise. You should not use exceptions to determine application behavior: they are expensive and unintuitive for other programmers who have to maintain your code.

I highly recommend Erip Lippert's immortal words on this topic: http://blogs.msdn.com/b/ericlippert/archive/2008/09/10/vexing-exceptions.aspx

Haney
  • 32,775
  • 8
  • 59
  • 68
  • 1
    I have another opinion on this. The exception should be thrown then when it is unknown what should be done as next step. If the program state is not as it should be in current step and you do not know what to do to cover it, Throwing an exception is the best thing you do at that moment. The article do you have do not claim that you should not used exception. You should not take the advantage of exception occurrence to control your application. – Damian Leszczyński - Vash Aug 05 '13 at 16:39
  • I think we're saying the same thing in slightly different ways. The thing is, the OP can recover the state of the app by checking for validation result to be true/false, WITHOUT exception being used. – Haney Aug 05 '13 at 16:48