«  两篇关于 Java & Unicod...   |   Blog首页   |   native2ascii - Nat... »

2006/04/27

Return Code Vs Exception from Validation Method

来自sun javaforum 的一些观点:

Return Code Vs Exception from Validation Method
Author: pks27  Posts: 2   Registered: 6/29/05
Jun 29, 2005 8:02 PM

From browser, my application receive some data. In code I validate input data and need to return error if validation fails. Which is better approach ?
1) Return Code. 0 for successful and non-zero for error
2) Throw appropriate business exception for error and normal termination of method in case of success.

Please suggest.

Thanks in advance
Praveen

 

Using return code will enforce you or others to process it or otherwise user won't be informed about mistake - but it is always possible to ignore it and bad things may happen. On the other hand throwing an exception is easier to handle in generic way and can be much more descriptive but clumsy if needs to be handled right in place of invocation.

So, looking from i18n point of view and user friendliness, I would implement it as a exception with support for human friendly localized and meanfull message. I would consider either checked or unchecked exception. From programmer point of view I would also consider declaring one root exception class for all kinds of validation errors and separate subclass of each kind - it will allow cause sensitive handling in try-catch syntax.

To get descriptive message with "return error code" way you will be expected to provide code2message method (or something like this).

If you decide to the "return error code" method I would rather return null in case of succes and non-null descriptive object (aka string) in case of error. Do not forget then about some king of .getCode method which will allow cause sensitive handling.

regards,
Tomasz Sztejka
 
Thanks for your input.

But I have one concern. Suppose you have around 15 rows in screen and one row contains about 10 items, where user can enter values. So if we write so many validation method throwing exception, don`t you think that it will have bad impact on performance.

Praveen
 
Looks like we have performance hit while we actually throw an exception? And no performance hit while normal program flow?

Denis Krukovsky
http://dotuseful.sourceforge.net/
http://dkrukovsky.blogspot.com/
 
> Thanks for your input.
(...)
>. So if we write so many
> validation method throwing exception, don`t you think
> that it will have bad impact on performance.

Throw/catch is in fact more time consuming than regular return. In this case, since input comes from human (very slow input rate) it does not matter. The big advantage of exceptions is that handling validation failures may be located somwhere far away from the place where validation was invoked. It realy makes UI design easier. But decission have to be yours.
 
When a user fills in a form, what's the likeliness that they'll enter something incorrectly, e.g. a malformed date or an invalid number. Very high, I'd say. Therefore, is invalid form data an exceptional condition? No.

If you only need to return a single value from your validation method, then the obvious choice is a boolean - true if the form was valid; false otherwise.

If, however, you need to present a list of validation failures, i.e. which fields were in error and why, then you could implement the passing parameter pattern, e.g.
	public class MyValidator {  public void validate(ValidationResult result) {    if (!(fieldX > 1 && fieldX < 10)) {      // A message key, rather than the actual message, would be more approriate.      result.addError("Field x must be greater than {0} and less than {1}.", 1, 10);    }    else if (...) {    }  }}// client code...MyValidator validator = ...ValidationResult result = new ValidationResult();validator.validate(result);if (result.containsErrors()) {  List errors = result.getErrors();  // do something with the errors.}
	
Passing the result as a parameter provides a certain degree of flexibility. e.g. You can have several different 'validators' (if necessary) to which you pass the result object, which collects the errors as it is passed around.
 
Nice idea - with exception there is no way to cumulate infos about errors found in multiple validations.
 

   
This topic has 6 replies on 1 page.

比较赞同这个观点: 

Throw/catch is in fact more time consuming than regular return. In this case, since input comes from human (very slow input rate) it does not matter. The big advantage of exceptions is that handling validation failures may be located somwhere far away from the place where validation was invoked. It realy makes UI design easier. But decission have to be yours.

阿涂 发表于 2006-04-27 09:56  阅读(400) 评论( 0) 引用( 0) Java
所有人可见

  • 收藏文章:
  • save at del.icio.us
  • save at digg
  • save at my yahoo
  • save at blinklist
  • save at furl
  • save at simpy
  • save at blogmarks
  • submit at reddit
  • save at spurl
  • save at shadows
  • save at rawsugar
  • save at bloglines

引用

http://www.uuzone.com/app/trackBack.do?type=blog&trackBackID=98792

相关内容
更多..

回复列表每两分钟自动刷新一次,想立即刷新吗?点击这里

您的浏览器可能不支持Frame, 优友地带需要使用Frame才能显示正常页面!