JAVA面試(5)

來源:互聯網
上載者:User

標籤:面試   有一個   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)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.