hung-doan / .bookmarks

My life bookmarker
0 stars 0 forks source link

Should I thdown exceptions for data validation #72

Open hung-doan opened 5 years ago

hung-doan commented 5 years ago

http://www.informit.com/articles/article.aspx?p=2923212&seqNum=9

Developers should make an effort to avoid throwing exceptions for expected conditions or normal control flow. For example, developers should not expect users to enter valid text when specifying their age.7 Therefore, instead of relying on an exception to validate data entered by the user, developers should provide a means of checking the data before attempting the conversion. (Better yet, they should prevent the user from entering invalid data in the first place.) Exceptions are designed specifically for tracking exceptional, unexpected, and potentially fatal situations. Using them for an unintended purpose such as expected situations will cause your code to be hard to read, understand, and maintain.

DO NOT use exceptions for handling normal, expected conditions; use them for exceptional, unexpected conditions

e.g : I expected user will type invalid data.

  1. If you think that 99% of the time this won't happens because It should be input the valid data. for example the client validation notwork, so that you get into the unexpected case (you don't expect it happen) Then go with throwing an Exception

  2. If you do not sure if user input valid data or not, it happens more frequency in your expectation . Because the validation just can be done during the calculation process (you expect it will happen, some time) Then go with returning an validation error