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

后端 未结 8 1898
攒了一身酷
攒了一身酷 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: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.

提交回复
热议问题