Is it a good or bad idea throwing Exceptions when validating data?

后端 未结 14 918
你的背包
你的背包 2020-12-07 16:27

When validating data, I\'ve gotten into a habit of doing the following:

Note: I don\'t really have individual booleans for each check. This is just

14条回答
  •  無奈伤痛
    2020-12-07 16:55

    It really only matters if your data validation is in a tight loop. For most cases, it doesn't matter what you choose as long as you are consistent in your code.

    If you have a lot of code that looks like your sample above then you might want to clean it up by introducing a helper method to throw...

    private void throwIf( bool condition, String message )
    {
        if( condition )
            throw new ApplicationException( message );
    }
    

    (also, doing this will help zero in on errors such as "validCheckOne = false" versus "validCheckOne == false" :)

提交回复
热议问题