天天看点

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.

如果有可能,尽量不使用静态方法和静态属性。 这个不是好的面向对象的编程风格,同时会给你测试代码带来困难。