Why are Exceptions said to be so bad for Input Validation?

后端 未结 17 1362
萌比男神i
萌比男神i 2020-11-30 20:37

I understand that \"Exceptions are for exceptional cases\" [a], but besides just being repeated over and over again, I\'ve never found an actual reason for this fact.

<
17条回答
  •  自闭症患者
    2020-11-30 21:12

    When I see exceptions being thrown for validation errors I often see that the method throwing the exception is performing lots of validations all at once. e.g.

    public bool isValidDate(string date)
    {
        bool retVal = true;
        //check for 4 digit year
        throw new FourDigitYearRequiredException();
        retVal = false;
    
        //check for leap years
        throw new NoFeb29InANonLeapYearException();
        retVal = false;
        return retVal;
    }
    

    This code tends to be pretty fragile and hard to maintain as the rules pile up over the months and years. I usually prefer to break up my validations into smaller methods that return bools. It makes it easier to tweak the rules.

    public bool isValidDate(string date)
    {
        bool retVal = false;
        retVal = doesDateContainAFourDigitYear(date);
        retVal = isDateInALeapYear(date);
        return retVal;
    }
    
    public bool isDateInALeapYear(string date){}
    
    public bool doesDateContainAFourDigitYear(string date){}
    

    As has been mentioned already, returning an error struct/object containing information about the error is a great idea. The most obvious advantage being that you can collect them up and display all of the error messages to the user at once instead of making them play Whack-A-Mole with the validation.

提交回复
热议问题