Tuesday, January 31, 2012

My Wicket improvement for StringValue was supported!

Working with Wicket I was sadly surprised by the behaviour of StringValue class. I needed to get optional parameters from URL, such as page number or document id. This parameters may have values, but can be omited and should be replaced by default value.

So I used this code to get page number, default page is 1.

PageParameters parameters = ...
int currentPage = parameters.get("page").toInt(1);  // default value is 1


Unfortunatelly, toInt(1) throwed StringValueConversionException instead of returning 1.



I submitted this improvement to Wicket Jira.  WICKET-4356 : StringValueConversionException thrown when calling toInt(final int defaultValue) on StringValue. Why not to return the default value?



Another Wicket user Robert McGuinness experienced the same:

i ran into this issue as well, kinda wish the api would fail silently upon conversion and return defaults. Ex:
http://wicket-stateless.herokuapp.com/?counter=8 (works)
but I forgot to check for non ints so the following will fail (will be fixed soon)
http://wicket-stateless.herokuapp.com/?counter=fails

This issue was also discussed in org.apache.wicket.dev discussion group. 

Martin Grigorov:

Hi devs,

At https://issues.apache.org/jira/browse/WICKET-4356 the reporter asks a reasonable question: why toXyz(default) throws a FormatException instead of returning the default value ? I agree with him. Is there a reason for the current behavior - the default value is used only if the text is null or empty but if non-empty and with the wrong format then the methods throw exception instead of logging it (DEBUG) and returning the default value.

If you also agree then the next question is: should we change this behavior in 1.5.x or just in 6.0?  

Sven Meier:

I don't know the reason for this. Let's change it for 1.5.x too.

Igor Vaynberg:

+1

Peter Ertl:

+1 avoiding try..catch() for the simplest of use cases makes sense for me

And finally, the issue was solved by Martin Grigorov:

The behavior of all methods "toXyz(default)" has been changed as requested. 


P.S. I am really happy to know that my idea was supported by the developers/maintainers of Wicket, because this small change would save many lines of try-catch, make code more secure and conversions would behave in a natural way. 


No comments:

Post a Comment