Is it a good practice to throw an exception on Validate() methods or better to return bool value?

后端 未结 8 1853
攒了一身酷
攒了一身酷 2020-12-28 14:24

Is it recommended or not to throw exceptions from Validation methods like:

ValidateDates();
ValidateCargoDetails();

Apart from this : Is t

相关标签:
8条回答
  • 2020-12-28 14:26

    Throwing exception must not be used to control the flow of the application. As the name implies, it happens in exceptional cases while validation could commonly fail. They are also expensive and impact the performance.

    I would go with returning a boolean plus a string for reason.

    0 讨论(0)
  • 2020-12-28 14:26

    Users entering invalid data is the very definition of an exception. When writing business requirements for a solution you always write the non-error paths as the main flow and error paths as exceptional paths. Using exceptions for validation is perfectly acceptable. Validating with exceptions also allows you to prioritise the order in how they are handled and to handle the error differently depending on what level you are at in the architecture stack (a string describing the error is of little use at the Data Access Layer).

    0 讨论(0)
  • 2020-12-28 14:37

    I usually use visitor pattern for validating input; accumulating all the errors into a list or something to show the user. The logic goes like, checking the list for validation errors, if found, inform the user, otherwise good to go.

    IMO, validation errors are not something exceptional, hence it should not be dealt like one.

    0 讨论(0)
  • 2020-12-28 14:44

    To be honest I'm quite on the fence on all of this. Sometimes I'm also building a visitor pattern, but it really feels I'm just re-implementing Exceptions.

    What I definitely don't like about the visitor pattern is that if your six levels deep and you notice that you need to break off you have to check the result at every level above.

    It means a lot of boilerplate code that actually can introduce bugs.

    Example What if you checked A - it doesn not validate, but the code continues checking B that actually depends on a proper initialized A? In complicated validation logic this can happens on a lot of different paths. It is error prone.

    On the other hand I used (custom) ValidationExceptions and haven't come across any significant problems. You hit something that does not validate and you are ensured that all the other validation logic will be skipped. This is a big win for simplicity of code.

    "Throwing exception must not be used to control the flow of the application." - for 99% of the other cases I would agree, but hanging on to this for validation logic seems to me based on dogma, not on pragmatism.

    About performace: Performance reasons are 99% not a concern in validation logic for user input, as this is almost never is done in tight loops.

    Summary: I recommend ignoring the "Exceptions are for Exceptional things" dogma, create (custom!) Exceptions that you throw and catch on the top level and see if it works for you. For me it does.

    0 讨论(0)
  • 2020-12-28 14:44

    I just wanted to bring this into the picture, answer of RADZSERG to the blog: Why throwing exceptions is better than returning error codes.

    In short - we do not need to limit ourselves to use boolean as a return type...

    I’m not telling that we should use or not to use Exception

    but as for that specific article – you build bad code at the beginning then tries to make it better. Build good code at the beginning and the explain why it’s better when we use exception. Here’s my example

    class TooManyLoginAttempts extends ValidationError{}
    
    if ($hasTooManyLoginAttempts) {
        return new TooManyLoginAttempts()
    }
    ...
    $validationResult = $this->validate();
    if ($validationResult instanceof ValidationError) {
        $this->errorLogger->log($validationResult->getMessage());
    }
    

    it also solves all described problems
    – no magic numbers
    – we’re solving the problem of having the error code across our entire application
    – my code is much shorter and also follows open-close principle

    I came here from: Is it a good practice to throw an exception on Validate() methods or better to return bool value? which is locked.

    0 讨论(0)
  • 2020-12-28 14:48

    Alot depends on how exceptional validation failures are are how critical it is to be correct.

    If your validation failures are rare and severe or fatal when they occur, I would use Exceptions or even AssertionErrors. Most parsers use Exceptions and these indicate it is not possible to continue processing.

    If your validation failure are expected as under normal operations and do not indicate you cannot continue processing, I would suggest using a visitor pattern or return a List of issues (which can be empty)

    0 讨论(0)
提交回复
热议问题