开发者

Best Practice - Validating Input In Simple GUI Application?

I'm writing a GUI app with wxwidgets in C++ for one of my programming classes. We have to validate input and throw custom exceptions if it开发者_开发百科 doesn't meet certain conditions. My question is, what is best practice when it comes to this? Should I write a seperate function that checks for errors, and have my event handler's call that function? Or should I do my error-checking in my event handlers? Or does it really matter?

Thanks!


Throwing exceptions for this seems a little odd.

I've always felt that a GUI app should prevent invalid data from even being entered in a control, which can be done using event handlers. For data that is inconsistent between several controls on a form, that should be validated when OK is pressed or whatever, and if the data isn't OK, prevent the form from closing and indicate the error.

The validation can also be done prior to pressing OK, but it shouldn't prevent the data being entered, only indicate the problem (and perhaps disable the OK button until its fixed). Basically, the inconsistent value entered in this control may not be inconsistent once the user has edited the value in the next control he's moving on to.

Try to avoid message boxes for reporting these errors - a status bar or a read-only text control within the form is better.

A function/method should be defined that does all the consistency checks for the form, but it shouldn't throw an exception. Bad input isn't the "exceptional" case from typical users - it happens all the time, especially when I'm the user. More to the point, you should only use exceptions when error-handling would otherwise mess up the structure of your code, which shouldn't be the case in an "is the data in this form OK - yes, fine, accept and close" event handler.

The function should just return an error code to indicate which error to report - or report the error itself and return an error flag.

Not so long ago, wxWidgets wasn't even exception-safe - IIRC, you still have to enable exception-safety as an option when you build the library.


You are raising a bigger concern than that, in fact. To answer your question, you can factor the validation code to a different function if you have, say, multiple widgets requiring the same validation. Or just because you see it fit -- it's up to you.

But the decision of where error handling should be is a more architectural question. Consider design by contract, which means any method assumes its parameters or input are in a valid state, and guarantees that its output or return value is valid as well. This implies that you should validate the user's input as soon as possible, rather than have the internal logic take care of that.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜