| « The Little Red Switch | I Guess So, Computer Skills, and The Temporary Offices » |
"While browsing the code base of a recently inherited project," Joey L writes, "I found this curious method."
private String insertComma(String src){
StringBuffer result = new StringBuffer();
try {
char d = '"';
result.append(d);
result.append(src);
result.append(d);
} catch (RuntimeException e) {
logger.error(e);
}
return result.toString();
}
"In addition to the strange indentation, I noticed three issues with this code."
"1. What is the try/catch for?
2. Why is the delimiter not a class variable or a parameter?
— and finally —
3. What the $§%& does the method name to do with the content?
Joey continued, "while the world does not have an answer to every stupid question, I can at least provide an answer to the last question. Here's the 'syntax' to use the method from above."
String result = ... + insertComma(varA) + "," + insertComma(varB) + ...;
"Hopefully that clears some things up."
Not only does using a StringBuffer yourself result in needless wordiness, it also generates more bytecode. If you use String concatenation over a StringBuilder, it'll be simpler: public class Test {
public static java.lang.String methodA(java.lang.String); public static java.lang.String methodB(java.lang.String); I realize the code isn't the same in both examples, I took the original method and changed it to what I would probably write (if I wrote something like that). As for returning an empty String if a RuntimeException occurs: If a RuntimeException occurs when you're prepending and appending quotation marks to a String, you probably shouldn't continue as if nothing is wrong. Letting that RuntimeException bubble up to someplace you can actually do something about it, like displaying "Fatal error, program can not continue" to the user would be better. This assumes you can even do that. Once a RuntimeException has occurred, it's unlikely you will be successful trying to build a message and dialog box to display to the user. |
| « The Little Red Switch | I Guess So, Computer Skills, and The Temporary Offices » |