Wednesday, 19 December 2007

Effective Java by Bloch - First

Splendid book about pure java coding about common errors as well as good developer java templates.

I tried to summary it:

- To enforce object to be singleton do private constructor and write static method getInstance. Such objects to be serialized has to have method readResolve() declared.
- If class is not to be instantiated as well as it's subclasses do private constructor. It will prevent this things. To make instance of class it have to has possibility to call superclass constructor
- Avoid creating duplicate objects
- Eliminate obsolete object references. If references are in array and are not longer needed so do not forget to null them out.
- Avoid finalizers. Where are run be garbage collector and can have on other VM other specification f.e. very low priority. Make sure your finalizer call superclass one. It is good practice to use in class private anonymous class do things to do making sure our subclass will call it on garbage collection even if finalizer method was overridden.
- Be careful with equals method for class and it's subclasses, f.e. mixing usage Timestamp and Date in same collection can give strange errors, while first extends second, and equals method is not transitive!
- Compare values: float by Float.floatToIntBits, double Double.doubleToLongBits
- when you override equals you should also override hashCode method so equal objects return same value. It is needed for hash Collections to work as thought to be. Best to has no hashCode same if values are not equal.
- when you write clone method you should not use final properties in Object
- Cloneable interface is for cloning objects and what we have to do to produce clone of object by calling in our clone method method from superclass super.clone()
- Comparable interface is for allowing sorting objects in java Collections using it's compareTo method. If objects should not be compared then method should throw ClassCastException. Restriction to method is that it has toobey reflexivity, symmetry, transitivity and not-nullity. Objects whose methods compareTo returns 0 should also return true through equals method to have same behavior in sorted an not sorted Collections.






No comments: