EL hidden dangers
31 May 2008 Tags:jsp
I was playing around with the expression language engine shipped as part of the Seam for some time. So: I created some utility component (let’s call it StringUtils(@Name=”stringUtils
It was tricky to realize the way I misunderstood the EL behaviour. I thought (rarely thoughts come out from my head) that passing value from *.jsf view into El expression - will result in invocation with this value as parameter.
Aha, sure :) Sure not. It depends what the type of the parameter is and what’s the value (thanks God, unit tests opened my eyes and made me to read through SPECS).
Defining Default Values Like many scripting languages, EL is forgiving of null values. When it can, EL simply substitutes an empty string, or zero, for null. The problem with this behavior is that sometimes you want to have special behavior if the value is null.
So. So, EL can do whatever it wants with Your parameters.
Let it show (from stringUtils):
public String capitalizeFirstCS(CharSequence s) {
if (s == null)
return null;
if (s.length() <= 1) {
return s.toString().toUpperCase();
}
//
return s.subSequence(0, 1).toString().toUpperCase().concat(
s.subSequence(1, s.length()).toString());
}
And
public String capitalizeFirstStr(String s) {
... basically the same code ..
}
And usage samples:
See the difference. As specs say - substitute "" for NULLs where possible. Hmmm. Char sequence couldn't be substituted? May be.. Or maybe it's just concrete implementation specifics (needs to be checked).
#{stringUtils.capitalizeFirstCS(null)} passes NULL
#{stringUtils.capitalizeFirstCS('')}, passes ""
#{stringUtils.capitalizeFirstCS('string')} passes "string"
#{stringUtils.capitalizeFirstStr(null)} passes ""
#{stringUtils.capitalizeFirstStr('')}, passes ""
#{stringUtils.capitalizeFirstStr('string')} passes "string"
Conclusion:
All I can tell - writing the code supposed to be called from EL isn't as simple it may look like, You may become foolished by sideEffects (String vs CharSequence, NULL for special meanings etc ..)
NB. If you've found typos or errors, please suggest a correction or edit on github.