2007年5月15日星期二

Trailing ","? No Problem!

Dushan Hanuska was generating code when he made the mistake of adding a trailing comma to the final element in an array initialization. Only the mistake turned out not to be a mistake. Here is the codeList initList = Arrays.asList(new Integer[] {new Integer(1),new Integer(2),new Integer(1),new Integer(2),});Dushan was quite surprised to see that his IDE didn't complain. He was even more surprised to find that the code not only compiled but ran perfectly ok.His curiosity lead him to the Java Language Specification where in section 10.6 he discovered that "A trailing comma may appear after the last expression in an array initializer and is ignored". Mystery solved.The interesting about sharing discoveries such as this is sometimes you can learn even more from people who leave comments. In this instance you may be surprised to learn that this is also a feature in JavaScript. As you could imagine, this helps normalize code generation code.

Message #226933 Post reply Post reply Post reply Go to top Go to top Go to top
Traling "," in JavaScript
Posted by: Michael Holtermann on ?? 06, 2007 in response to Message #226930
In this instance you may be surprised to learn that this is also a feature in JavaScript.But be aware: A snippet like this:dojo.io.bind({ url : 'somewhere.do', handler: replaceFilterSelection, mimetype: "text/html", content: {attribute: "test"}, });(see the trailing comma after content) will work in Firefox, but lead IE to errors...Greetings, Michael.

Message #227025 Post reply Post reply Post reply Go to top Go to top Go to top
Useful in Enums
Posted by: Macneil Shonle on ?? 06, 2007 in response to Message #226933 I found this to be useful in an Enum I was recently making:enum ModifierElement {... MOD_PUBLIC("public"), MOD_PROTECTED("protected"), MOD_PRIVATE("private"), MOD_DEFAULT("default")/*special default-access specifier*/, ;...}I wanted my comment to be seen as unmistakably about the MOD_DEFAULT member. Had I not added the comma I could have ended up adding or changing the list later on, being just one autoformat away from it looking like I was commenting on the next element instead.Using the trailing comma is similar to always using braces: it can look cluttered, but it makes copying and pasting lines of code (and other modifications) much easier.

没有评论: