天天看點

Java程式設計的幾個最佳實踐

看smack的時候,發現作者提出了幾個開發的實踐(http://community.igniterealtime.org/docs/DOC-1984),轉載過來,并初步翻譯了一下[抱歉,翻譯的有點爛],雖然很容易了解,但很有意思,對我們的程式設計有借鑒意義。

  • To convert a primitive to a String use String.valueOf(...). Don't use "" + i.

從基本類型轉成String類型,用String.valueOf(...), 不要用""+i。

  • To convert from a primitive use Integer.parseInt(...) and similar.

基本類型轉換, 使用 Integer.parseInt(...), 其他的類型也有類似的方法。

  • Don't use StringBuffer unless you need threadsafety, use StringBuilder instead.

除非你需要線程安全,你可以使用StringBuffer。 否則,使用StringBuilder。

  • Similarly don't use Vector, use ArrayList.

與上一條類似的理由,使用ArrayList而不是Vector。

  • Code to interfaces instead of specific implementations (Collection or List instead of ArrayList).

面向Interface程式設計,不要面向實作程式設計(例如,使用Collection或者List等借口,不要使用ArrayList這樣的具體實作)。

  • Never subclass Thread, always pass a Runnable into the constructor instead.

不要子類Thread, 多使用構造函數+Runnable的方式來使用線程。

  • If equals is implemented in a class it is MANDATORY to implement hashCode as well, otherwise HashSets and other classes which rely on the contract of hashCode will not work. IDEs like Eclipse provide generators to implement equals and hashCode.

如果實作了equals方法,那麼必須實作hashCode方法,否則,類似HashSets等依賴hashCode來做比較的類無法工作[注:HashSets等方式是通過Key的hashCode定位數組中存放的具體位置清單,然後通過equals方式來擷取清單中具體的元素。如果hashCode相同,會産生HashCode拒絕攻擊] Eclipse等IDE提供了代碼産生器,可以幫助實作equals和hashCode方法。

  • Use enum instead of a bunch of static final int fields. Then you have type safety for related constants and more readable debugging output is possible because you get meaningful names instead of "magic" numbers.

不要使用靜态常量,而是使用enum。 這樣,你就可以得到更安全的類型常量,并且調試輸出更具有可讀性,因為你能看到有意義的名字,而不是“魔術”數字。

  • Avoid the use of static methods and attributes if possible. This is not good object oriented programming style and it also makes testing your code more difficult.

如果有可能,盡量不使用靜态方法和靜态屬性。 這個不是好的面向對象的程式設計風格,同時會給你測試代碼帶來困難。