Company Ghost Story 公司鬼故事 10

contents

  1. 1. Java
    1. 1.1. Compare Function
    2. 1.2. Partition Function
    3. 1.3. Try-Catch vs. If-Else

Java

Compare Function

1
2
3
4
5
6
7
Collections.sort(arr, (x, y) -> (int) (x.cost - y.cost));
Collections.sort(arr, (x, y) -> Long.valueOf(x).compareTo(y));
Collections.sort(arr, (x, y) -> (int) Math.round(x.cost - y.cost));
// why not use official methods?
Collections.sort(arr, (x, y) -> Double.compare(x.cost, y.cost));
Collections.sort(arr, (x, y) -> Long.compare(x, y));

別鬧了,會 overflow/underflow,數量一大,每一個排序都在丟例外給我啊。

Partition Function

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Optimizer {
private int avgX(ArrayList<Point> pts) {
ArrayList<Long> x = new ArrayList<>(pts.size());
for (Point p : pts)
x.add(p.x);
return avg(x);
}
private int avg(ArrayList<Long> xs) {
long sum = 0;
for (Long x : xs)
sum += x;
return sum / xs.size();
}
}
// ... why not merge avg() into avgX()?

每次都要額外建一個陣列,而且這個函數只有被內部的單一函數呼叫,函數切這麼細,但是效能卻爛掉。

Try-Catch vs. If-Else

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Parser {
void addChar(char c) {
try {
que[index] = c;
} catch (ArrayIndexOutOfBoundsException e) {
doubleArray();
que[index] = c;
}
index++;
}
}
// why not just write if-else statements, it's really hard to maintain your code.
class Parser {
void addChar(char c) {
if (index >= que.length)
doubleArray(index);
que[index] = c;
index++;
}
}

如果在修改這幾段代碼的時候,還得經常考慮例外處理是怎麼做的,這寫法真的太奇葩。要是開剖析器去檢查,會經常看到例外出現,那到底是好事還壞事?