2017年11月1日 星期三

Day1-2 - 識別字和JavaBeans

1.3 Develop code that declares, initializes, and uses primitives, arrays, enums, and objects as static, instance, and local variables. Also, use legal identifiers for variable names.


1.4 Develop code that declares both static and non-static methods, and - if appropriate - use method names that adhere to the JavaBeans naming standards. Also develop code that declares and uses a variable-length argument list.

合法識別字 (Legal Identifier)

編譯器判斷一個名稱是否合法的規則
  1. Identifier必須以字母開頭,也可以使用"_"與"$"作為開頭
  2. 第一個字元以後,可包含任何字母、$、"_"和數字
  3. 不能使用Keywords(關鍵字)當作識別字。從Java1.5後新增一個keyword: enum。
  4. Java的Identifier有區分大小寫; food和Food是不同的兩個識別字。
非法範例如下:(注意特殊符號只有底線和$可以當作Identifier的一員)

int :b;
int -d;
int e#;
int .f;
int 7g;

Java Code Conventions

  1. Class & Interface: 首字大寫,若有數個單字連載一起的話,則內部第一個字需大寫(camelCase)。Class基本上為名詞 (Animal)Interface基本上為形容詞 (ex: Runnable)
  2. Method: 第一個字母應小寫,再遵守camelCase。基本上為動詞-名詞配對(ex: getBalance)
  3. Variable: 第一個字母應小寫,建議簡短且有意義(ex: buttonWidth)。
  4. Constant: 透過標示static or final來建立。應使用大寫字元和底線做為區隔(ex: MIN_HEIGHT)。

JavaBean標準

Sun針對class, variable, method的命名方式所給的建議。透過制定來協助Java developer建立Java元件,使得Java developer能夠在IDE內使用。
JavaBeans是擁有properties(private instance variables)的Java類別。
- 要存取到properties唯一途徑就是透過setter methods(設值函數) and getter methods(取值函數)
- 命名規則

  1. 若property的type不是boolean,則getter metod prefix為get
  2. 若property的type是boolean,則getter method prefix為get or is (ex: getId(), isStopped())
  3. setter method prefix為set
  4. set, is, get之後為property名的第一個字母改成大寫,形成函數名
  5. setter methods的signature必須被標示成public,有一個argument,type為此property的型別,回傳void
  6. getter methods的signature也必須是public,沒有argument,有一個回傳型別(與此argument相同)

- 支援events。新增移除事件的listener metod必須遵守JavaBeans的命名標準

  1. register events: prefix須為add。ex: addActionListener()
  2. remove register: prefix須為remove
  3. 用來新增或移除listener的type必須當作argument傳入此method
  4. add or remove register method都必須以Listener結尾

非法範例如下:(注意特殊符號只有底線和$可以當作Identifier的一員)

void setCustomerName(String s) //必須是public

public void addXListener(MyListener m) //Listener type不一致

*Variable legal identifier也是一個method or class legal naming
*Note the JavaBeans 命名慣例

沒有留言:

張貼留言