標籤:面試 有一個 ror 判斷 compile row read 泛型 自己
這裡列出10條JAVA編程經驗
1 字串常量放在前面
把字串常量放在equals()比較項的左側來防止偶然的NullPointerException。
// Badif (variable.equals("literal")) { ... } // Goodif ("literal".equals(variable)) { ... }
2 不要相信-1
// Badif (string.indexOf(character) != -1) { ... }// Goodif (string.indexOf(character) >= 0) { ... }
3 避免意外的賦值
如果你的運算式中有常量,將它放在等式左邊。這樣當你打算再添加一個 = 時,不容易出錯。
// Ooopsif (variable = 5) { ... } // Better (because causes an error)if (5 = variable) { ... }// Intent (remember. Paranoid JavaScript: ===)if (5 === variable) { ... }
4 檢查NULL和長度
不管什麼時候你有一個集合、數組或者其他的,確保它存在並且不為空白
// Badif (array.length > 0) { ... }// Goodif (array != null && array.length > 0) { ... }
當然也可以用Collections.isEmpty() 判斷
5 所有的方法都用final聲明
你可以告訴我任何你想要的開閉原則,不過那都是胡說八道。我不相信你(可以正確繼承我的類),也不相信我自己(不會意外地繼承我的類)。因此除了介面(專門用於繼承)都應該是嚴格的 final
// Badpublic void boom() { ... } // Good. Don‘t touch.public final void dontTouch() { ... }
6 所有的變數和參數都用final聲明
// Badvoid input(String importantMessage) { String answer = "..."; answer = importantMessage = "LOL accident";} // Goodfinal void input(final String importantMessage) { final String answer = "...";}
7 重載的時候不要相信泛型
// Bad<T> void bad(T value) { bad(Collections.singletonList(value));} <T> void bad(List<T> values) { ...} // Goodfinal <T> void good(final T value) { if (value instanceof List) good((List<?>) value); else good(Collections.singletonList(value));} final <T> void good(final List<T> values) { ...}
8 總是在switch語句裡加上default
// Badswitch (value) { case 1: foo(); break; case 2: bar(); break;} // Goodswitch (value) { case 1: foo(); break; case 2: bar(); break; default: throw new ThreadDeath("That‘ll teach them");}
9 用大括弧隔開switch的每一個case塊
// Bad, doesn‘t compileswitch (value) { case 1: int j = 1; break; case 2: int j = 2; break; // j重複定義} // Goodswitch (value) { case 1: { final int j = 1; break; } case 2: { final int j = 2; break; } // Remember: default: throw new ThreadDeath("That‘ll teach them");}
JAVA面試(5)