常見的Java不規範代碼

來源:互聯網
上載者:User

1.格式化原始碼

Ctrl + Shift + F – 格式化原始碼。

Ctrl + Shift + O – 管理import語句並移除未使用的語句

除了手動執行這兩個功能外,你還可以讓Eclipse在儲存檔案的時候自動格式 化原始碼並自動管理import語句。要做到這個,在Eclipse中,到 Window -> Preferences -> Java -> Editor -> Save Actions並啟用 Perform the selected actions on save,選中 Format source code和 organize imports。

2.避免在方法中出現多個return語句(退出點)

下面的代碼是 不推薦的,因為它有多個退出點(return語句):

private boolean isEligible(int age){if(age > 18)return true; }else{return false;}}

上面的代碼可以這麼寫:

private boolean isEligible(int age){boolean result = false;if(age > 18)result = true; }Return result;}

還可以寫為:
private boolean isEligible(int age){return age>18;}
3.不要為Boolean,Integer或String建立新的執行個體

避免建立新的Boolean,Integer,String等執行個體。使用Boolean.valueOf(true)代替new Boolean(true)。兩種寫法效果差不多但卻可以改善效能。

4.用大寫命名public static final類型成員變數:

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.