Thursday, January 13, 2005

Java Tip #6 - Don't capitalize first two letters of a bean property name

This is in our java standards. You should not create a java bean property name that begins with a capital letter in the 1st two places. It can lead to confusing results. We had this happen a few times & finally added it to our standards & enforce it in code reviews. One place we saw problems was in struts. The form bean properties are used in the JSP page, but the Struts framework has to use the getter() & setter() to interact with the bean. This mapping happens based on the java bean spec & in certain cases can cause a method not found error if the developer doesn't name the method just right. The java bean spec provides guidelines on how to map between property and the associated getter() & setter().

The following is from the javabean spec at http://java.sun.com/products/javabeans/docs/beans.101.pdf .

8.8 Capitalization of inferred names.

Thus when we extract a property or event name from the middle of an existing Java name, we normally convert the first character to lower case. However to support the occasional use of all upper-case names, we check if the first two characters of the name are both upper case and if so leave it alone. So for example,

“FooBah” becomes “fooBah”
“Z” becomes “z”
“URL” becomes “URL”

We provide a method Introspector.decapitalize which implements this conversion rule.

Here’s the source code for Introspector.decapitalize().


public static String decapitalize(String name) {
if (name == null || name.length() == 0) {
return name;
}
if (name.length() > 1 && Character.isUpperCase(name.charAt(1)) &&
Character.isUpperCase(name.charAt(0))){
return name;
}
char chars[] = name.toCharArray();
chars[0] = Character.toLowerCase(chars[0]);
return new String(chars);
}
The following table shows how the 1st two characters map. If this was a mathematical function, I’d say it wasn’t one-to-one. (‘aa’ and ‘Aa’ imply the same getter)

property
-----------
getter
---------
aa getaa()
aA getaA()
Aa getaa()
AA getAA()


4 Comments:

Anonymous Anonymous said...

Believe it or not this tip really helped me out. Thanks a lot!

1:56 PM  
Anonymous Anonymous said...

Is it not rather like this?

property x getter
-----------------
aa = getAa()
aA = getaA()
Aa = getAa()
AA = getAA()

8:23 AM  
Blogger Stevo Slavić said...

This comment has been removed by the author.

3:42 AM  
Blogger Sky Ridder said...

everything mentioned above is wrong,its not working
I have scenario Wind_shrt is my field, and according to this post I have tried every possible solution to form getter/setter method, nothing helpful guys.

5:51 AM  

Post a Comment

<< Home