Company Ghost Story 公司鬼故事 8

contents

  1. 1. Java
    1. 1.1. Format String
    2. 1.2. Math
    3. 1.3. Variable Name
    4. 1.4. Initialize Member
    5. 1.5. Lambda with Final
    6. 1.6. Method Name
    7. 1.7. Context

Java

Format String

1
2
String.format("ABC%s", "D"); // const string should be written directly
String.format("%s.%s", A.class.getName(), "C");

對於可以直接計算得到的,應該直接展開。

Math

1
2
3
4
5
6
7
8
9
10
11
12
13
14
double theta = dx != 0 ? Math.atan(dy/dx) : (dy < 0 ? ... : ...);
// or
if (dx < 0) {
if (dy < 0)
...
} else (dx == 0) {
if (dy < 0)
...
}
// why not be simple?
double theta = Math.atan2(dy, dx);

數學很重要,可以減少很多分支判斷。

Variable Name

1
2
List<T> set = new LinkedList<>(); // what does `set` means?
// perhaps, I need to ask what does `list` means for you.
1
2
TextField okBtn; // why name button for text field?
enableCancelButton(okBtn); // are you sure about it?

命名盡量貼切型態,不然有時候真的會有很奇怪。

Initialize Member

1
2
3
4
5
6
7
8
9
10
11
12
class MPanel {
private JButton mButton;
public MPanel() { // consturctor
...
mButton = new JButton("A"); // what?
panel.add(mButton);
mButton = new JButton("B"); // what?
panel.add(mButton);
// finally, which result you want to express mButton?
}
}

在建構子中,每一個成員變數盡量只存放一次,採用 final 對每個成員變數檢查只初始化一次。

Lambda with Final

1
2
3
4
5
6
7
void process(...) {
String s = "default";
if (isA())
s = "A";
final String _s = s; // shut up, don't explain
blackhole(() -> map(_s));
}

Lambda 函數抓取的時候都要抓取可推斷出 final 的變數。為了 lambda 而額外宣告一個變數作為 final 的話,應該要額外宣告一個 getter 函數去抓取,不然觀感上會覺得代碼有點多餘。

Method Name

1
2
3
4
void increment() { // why is noun?
i++;
i++; // why call it twice?
}

函數盡量使用動詞開頭,名詞有點奇怪。

Context

1
2
3
4
5
6
7
void enableA() {
a = true;
b = true; // why is b here?
}
void disableA() {
a = false; // wait ... where is B?
}

當名稱對應到成員變數時,就應該一件事情對應一個操作。