你見過(guò)最爛的 Java 代碼是什么?
點(diǎn)擊“開發(fā)者技術(shù)前線”,選擇“星標(biāo)?”
在看|星標(biāo)|留言,? 真愛

作者:王超,花名麟超,
阿里巴巴高級(jí)地圖技術(shù)工程師,一直從事Java研發(fā)相關(guān)工作。
導(dǎo)讀
私欲日生,如地上塵,一日不掃,便又有一層。著實(shí)用功,便見道無(wú)終窮,愈探愈深,必使精白無(wú)一毫不徹方可。
Map<String, String> map = ...;
for (String key : map.keySet()) {
String value = map.get(key);
...
}
正例:
Map<String, String> map = ...;
for (Map.Entry<String, String> entry : map.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
...
}
if (collection.size() == 0) {
...
}
if (collection.isEmpty()) {
...
}
List<String> list = new ArrayList<>();
list.add("Hello");
list.add("World");
if (list.containsAll(list)) { // 無(wú)意義,總是返回true
...
}
list.removeAll(list); // 性能差, 直接使用clear()
int[] arr = new int[]{1, 2, 3};
List<Integer> list = new ArrayList<>();
for (int i : arr) {
list.add(i);
}
int[] arr = new int[]{1, 2, 3};
List<Integer> list = new ArrayList<>(arr.length);
for (int i : arr) {
list.add(i);}
String s = "";
for (int i = 0; i < 10; i++) {
s += i;
}
String a = "a";
String b = "b";
String c = "c";
String s = a + b + c; // 沒(méi)問(wèn)題,java編譯器會(huì)進(jìn)行優(yōu)化
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 10; i++) {
sb.append(i); // 循環(huán)中,java編譯器無(wú)法進(jìn)行優(yōu)化,所以要手動(dòng)使用StringBuilder
}List 的隨機(jī)訪問(wèn)
// 調(diào)用別人的服務(wù)獲取到list
List<Integer> list = otherService.getList();
if (list instanceof RandomAccess) {
// 內(nèi)部數(shù)組實(shí)現(xiàn),可以隨機(jī)訪問(wèn)
System.out.println(list.get(list.size() - 1));
} else {
// 內(nèi)部可能是鏈表實(shí)現(xiàn),隨機(jī)訪問(wèn)效率低
}頻繁調(diào)用 Collection.contains 方法請(qǐng)使用 Set
ArrayList<Integer> list = otherService.getList();
for (int i = 0; i <= Integer.MAX_VALUE; i++) {
// 時(shí)間復(fù)雜度O(n)
list.contains(i);
}
ArrayList<Integer> list = otherService.getList();
Set<Integer> set = new HashSet(list);
for (int i = 0; i <= Integer.MAX_VALUE; i++) {
// 時(shí)間復(fù)雜度O(1)
set.contains(i);
}
讓代碼更優(yōu)雅
長(zhǎng)整型常量后添加大寫 L
long value = 1l;
long max = Math.max(1L, 5);
long value = 1L;
long max = Math.max(1L, 5L);不要使用魔法值
for (int i = 0; i < 100; i++){
...
}
if (a == 100) {
...
}
private static final int MAX_COUNT = 100;
for (int i = 0; i < MAX_COUNT; i++){
...
}
if (count == MAX_COUNT) {
...
}
private static Map<String, Integer> map = new HashMap<String, Integer>() {
{
put("a", 1);
put("b", 2);
}
};
private static List<String> list = new ArrayList<String>() {
{
add("a");
add("b");
}
};
private static Map<String, Integer> map = new HashMap<>();
static {
map.put("a", 1);
map.put("b", 2);
};
private static List<String> list = new ArrayList<>();
static {
list.add("a");
list.add("b");
};建議使用 try-with-resources 語(yǔ)句
private void handle(String fileName) {
BufferedReader reader = null;
try {
String line;
reader = new BufferedReader(new FileReader(fileName));
while ((line = reader.readLine()) != null) {
...
}
} catch (Exception e) {
...
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
...
}
}
}
}
private void handle(String fileName) {
try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
String line;
while ((line = reader.readLine()) != null) {
...
}
} catch (Exception e) {
...
}
}
刪除未使用的私有方法和字段
public class DoubleDemo1 {
private int unusedField = 100;
private void unusedMethod() {
...
}
public int sum(int a, int b) {
return a + b;
}
}
public class DoubleDemo1 {
public int sum(int a, int b) {
return a + b;
}
}
刪除未使用的局部變量
public int sum(int a, int b) {
int c = 100;
return a + b;
}
public int sum(int a, int b) {
return a + b;
}
刪除未使用的方法參數(shù)
public int sum(int a, int b, int c) {
return a + b;
}
public int sum(int a, int b) {
return a + b;
}
刪除表達(dá)式的多余括號(hào)
return (x);
return (x + 2);
int x = (y * 3) + 1;
int m = (n * 4 + 2);
return x;
return x + 2;
int x = y * 3 + 1;
int m = n * 4 + 2;
工具類應(yīng)該屏蔽構(gòu)造函數(shù)
public class MathUtils {
public static final double PI = 3.1415926D;
public static int sum(int a, int b) {
return a + b;
}
}
public class MathUtils {
public static final double PI = 3.1415926D;
private MathUtils() {}
public static int sum(int a, int b) {
return a + b;
}
}刪除多余的異常捕獲并拋出
private static String readFile(String fileName) throws IOException {
try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
String line;
StringBuilder builder = new StringBuilder();
while ((line = reader.readLine()) != null) {
builder.append(line);
}
return builder.toString();
} catch (Exception e) {
throw e;
}
}
private static String readFile(String fileName) throws IOException {
try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
String line;
StringBuilder builder = new StringBuilder();
while ((line = reader.readLine()) != null) {
builder.append(line);
}
return builder.toString();
}
}
公有靜態(tài)常量應(yīng)該通過(guò)類訪問(wèn)
public class User {
public static final String CONST_NAME = "name";
...
}
User user = new User();
String nameKey = user.CONST_NAME;
public class User {
public static final String CONST_NAME = "name";
...
}
String nameKey = User.CONST_NAME;
不要用NullPointerException判斷空
public String getUserName(User user) {
try {
return user.getName();
} catch (NullPointerException e) {
return null;
}
}
正例:
public String getUserName(User user) {
if (Objects.isNull(user)) {
return null;
}
return user.getName();
}
使用String.valueOf(value)代替""+value
int i = 1;
String s = "" + i;
int i = 1;
String s = String.valueOf(i);
過(guò)時(shí)代碼添加 @Deprecated 注解
/**
* 保存
*
* @deprecated 此方法效率較低,請(qǐng)使用{@link newSave()}方法替換它
*/
@Deprecated
public void save(){
// do something
}
讓代碼遠(yuǎn)離 bug
禁止使用構(gòu)造方法 BigDecimal(double)
BigDecimal value = new BigDecimal(0.1D); // 0.100000000000000005551115...
BigDecimal value = BigDecimal.valueOf(0.1D);; // 0.1
返回空數(shù)組和空集合而不是 null
public static Result[] getResults() {
return null;
}
public static List<Result> getResultList() {
return null;
}
public static Map<String, Result> getResultMap() {
return null;
}
public static void main(String[] args) {
Result[] results = getResults();
if (results != null) {
for (Result result : results) {
...
}
}
List<Result> resultList = getResultList();
if (resultList != null) {
for (Result result : resultList) {
...
}
}
Map<String, Result> resultMap = getResultMap();
if (resultMap != null) {
for (Map.Entry<String, Result> resultEntry : resultMap) {
...
}
}
}
public static Result[] getResults() {
return new Result[0];
}
public static List<Result> getResultList() {
return Collections.emptyList();
}
public static Map<String, Result> getResultMap() {
return Collections.emptyMap();
}
public static void main(String[] args) {
Result[] results = getResults();
for (Result result : results) {
...
}
List<Result> resultList = getResultList();
for (Result result : resultList) {
...
}
Map<String, Result> resultMap = getResultMap();
for (Map.Entry<String, Result> resultEntry : resultMap) {
...
}
}
public void isFinished(OrderStatus status) {
return status.equals(OrderStatus.FINISHED); // 可能拋空指針異常
}
public void isFinished(OrderStatus status) {
return OrderStatus.FINISHED.equals(status);
}
public void isFinished(OrderStatus status) {
return Objects.equals(status, OrderStatus.FINISHED);
}public enum UserStatus {DISABLED(0, "禁用"),ENABLED(1, "啟用");public int value;private String description;private UserStatus(int value, String description) {this.value = value;this.description = description;}public String getDescription() {return description;}public void setDescription(String description) {this.description = description;}}
正例:
public enum UserStatus {
DISABLED(0, "禁用"),
ENABLED(1, "啟用");
private final int value;
private final String description;
private UserStatus(int value, String description) {
this.value = value;
this.description = description;
}
public int getValue() {
return value;
}
public String getDescription() {
return description;
}
}
"a.ab.abc".split("."); // 結(jié)果為[]
"a|ab|abc".split("|"); // 結(jié)果為["a", "|", "a", "b", "|", "a", "b", "c"]
"a.ab.abc".split("\\."); // 結(jié)果為["a", "ab", "abc"]
"a|ab|abc".split("\\|"); // 結(jié)果為["a", "ab", "abc"]
總結(jié)
這篇文章,可以說(shuō)是從事 Java 開發(fā)的經(jīng)驗(yàn)總結(jié),分享出來(lái)以供大家參考。希望能幫大家避免踩坑,讓代碼更加高效優(yōu)雅。
END 前線推出學(xué)習(xí)交流群,加群一定要備注:
研究/工作方向+地點(diǎn)+學(xué)校/公司+昵稱(如java+上海+上交+可可) 根據(jù)格式備注,可更快被通過(guò)且邀請(qǐng)進(jìn)群,領(lǐng)取一份專屬學(xué)習(xí)禮包 掃碼加我微信進(jìn)群 大廠內(nèi)推和技術(shù)交流,和前輩大佬們零距離 歷史推薦
Google 出品 Java 編碼規(guī)范,強(qiáng)烈推薦! Java程序員必備的11大Intellij插件 10個(gè)實(shí)用但非常偏執(zhí)的Java編程技巧 一款牛逼的Java工具類庫(kù),GitHub星標(biāo)10.4k+,你敢用嗎? 好文點(diǎn)個(gè)在看吧!
評(píng)論
圖片
表情


