• 1. Effective Java
  • 2. Version HistoryDateVersionSummary of ChangeAuthor?1.0Initially created.?06/11/20121.1Add chapters Enums & Annotation, Concurrency. Replace slide with new template.Benson Wu06/18/20121.2Add chapter ReflectionBenson Wu
  • 3. AgendaSerialization Creating and Destroying Objects Methods Common to all Objects Classes and Interfaces Generics Methods General Programming Enums and Annotations Concurrency Reflection
  • 4. Object serializationSerializing, encoding an object as a byte stream Deserializing, reconstructing objects from their byte stream encoding Why use serialize and deserialize Serialize and deserialize process writeReplace writeObject readObject readResolve
  • 5. Serialization Example
  • 6. The principle of using serializeImplement Serializable judiciously it decreases the flexibility to change a class’s implementation once it has been released it increases the likelihood of bugs and security holes it increases the testing burden associated with releasing a new version of a class classes designed for inheritance should rarely implement Serializable, and interfaces should rarely extend it Consider using a custom serialized form Write readObject methods defensively For instance control, prefer enum types to readResolve
  • 7. AgendaSerialization Creating and Destroying Objects Methods Common to all Objects Classes and Interfaces Generics Methods General Programming Enums and Annotations Concurrency Reflection
  • 8. Singleton(1)
  • 9. Singleton(2)
  • 10. Singleton(3)
  • 11. RulesCreate unique instance to avoid conflict Avoid duplicate initialization if it is costly Be care when implements Serializable in Singleton Don't use Singleton in distributed systems
  • 12. Avoid creating duplicate objectsFrugally use the key word new Invoke exists static factory method if possible Using Flyweight pattern if possible
  • 13. Understand String Pool
  • 14. Avoid finalizers Finalizers are unpredictable, often dangerous, and generally unnecessary Explicit termination methods are typically used in combination with the try-finally construct to ensure termination Finalizers is to act as a "safety net" to use
  • 15. AgendaSerialization Creating and Destroying Objects Methods Common to all Objects Classes and Interfaces Generics Methods General Programming Enums and Annotations Concurrency Reflection
  • 16. General Contract of EqualsReflexive x.equals(x) must be true Symmetric If x.equals(y) == true, then y.equals(x) Transitive If x.equals(y) and y.equals(z), then x.equals(z) == true Consistency If x.equals(y) == true, then always x.equals(y) == true if there is no modification with x and y Null values x.equals(null) is always false
  • 17. Always override hashCode when you override equals HashCode must return same integer on different calls, as long as equals() unchanged If x.equals(y), then x, y have same hashcode It is not required that unequal objects have different hashcodes
  • 18. Always override toString Return all "significant" information If you specify a format, be precise Others may parse your toString representations API should include access to all information contained in toString() representation Otherwise, others are forced to parse representation
  • 19. Override Clone Judiciously Deep Clone vs Flat Clone Invoking super.clone() when override Ensure that it does no harm to the original object when override
  • 20. AgendaSerialization Creating and Destroying Objects Methods Common to all Objects Classes and Interfaces Generics Methods General Programming Enums and Annotations Concurrency Reflection
  • 21. Minimize the accessibilityMembers fields, methods, nested classes, and nested interfaces Access level private, package-private, protected, public Develop Rules Instance fields should never be public,accessor its by methods Don't use static final array field, or an accessor that returns such a field
  • 22. Immutable Class - ReasonsEasier to design Easier to implement Easier to use Less prone to error More secure Easier to share Thread safe
  • 23. Immutable Class - RulesDon’t provide any methods that modify the object’s state Ensure that the class can’t be extended Make all fields final Make all fields private Ensure exclusive access to any mutable components
  • 24. Immutable Class - Disadvantage And SolutionDisadvantage Too many instances for distinct values Performance Solution Provide mutable companion class for situations where performance is an issue Example in Java Library String (Immutable) StringBuffer (Companion Mutable Class)
  • 25. Favor composition over inheritanceInheritance breaks encapsulation
  • 26. Design document for inheritanceDocument overridable method behavior precisely Document any circumstances overridable method being invoked Document dependent overridable methods Or avoid coupling between overridable methods Or minimize number of overridable methods (hooks) Constructors must not invoke overridable methods clone() & readObject() must not invoke overridable methods readResolve() or writeReplace() protected
  • 27. Use programming interfacePrefer interfaces to abstract classes Existing classes can be easily retrofitted to implement a new interface Interfaces are ideal for defining mixins Interfaces allow the construction of nonhierarchical type frameworks Interfaces enable safe, powerful functionality enhancements Use interfaces only to define types
  • 28. AgendaSerialization Creating and Destroying Objects Methods Common to all Objects Classes and Interfaces Generics Methods General Programming Enums and Annotations Concurrency Reflection
  • 29. Motivating ExampleBeforeNow
  • 30. Why do we need GenericsGenerics allow us to abstract over types Generics increase the readability of the procedure Generics increase the safety of the generic types Compile check Runtime Safety
  • 31. Use Generics Rules(1)Don’t use raw types in new code Eliminate unchecked warnings: Every time you use an @SuppressWarnings("unchecked") annotation,add a comment saying why it’s safe to do so Prefer lists to arrays
  • 32. Use Generics Rules(2)Favor generic param typesFavor generic methods
  • 33. AgendaSerialization Creating and Destroying Objects Methods Common to all Objects Classes and Interfaces Generics Methods General Programming Enums and Annotations Concurrency Reflection
  • 34. Check parameters for validity
  • 35. Use defensive copy when needed(1)
  • 36. Use defensive copy when needed(2)Solution
  • 37. Use overloading judiciously
  • 38. AgendaSerialization Creating and Destroying Objects Methods Common to all Objects Classes and Interfaces Generics Methods General Programming Enums and Annotations Concurrency Reflection
  • 39. Minimize the scope of local variablesThe most powerful technique for minimizing the scope of a local variable is to declare it where it is first used Nearly every local variable declaration should contain an initializer Prefer for loops to while loops Keep methods small and focused
  • 40. Other Base RulesPrefer use the libraries Refer to objects by their interfaces Prefer interfaces to reflection Optimize judiciously Adhere to generally accepted naming conventions
  • 41. Avoid float and double if exact answers are requiredThey do not provide exact results and should not be used where exact results are required They are particularly ill-suited for monetary calculations Use BigDecimal, int, or long for monetary calculations
  • 42. AgendaSerialization Creating and Destroying Objects Methods Common to all Objects Classes and Interfaces Generics Methods General Programming Enums and Annotations Concurrency Reflection
  • 43. Enums Rules (1)Use enums instead of int constants easy to read compile-time type safety check add arbitrary methods and fields and implement arbitrary interfaces
  • 44. Enums Rules (2)Use instance fields instead of ordinalsNever derive a value associated with an enum from its ordinal; store it in an instance field instead.
  • 45. Enums Rules (3-1)Emulate extensible enums with interfaces
  • 46. Enums Rules (3-2)Summary: while you cannot write an extensible enum type, you can emulate it by writing an interface to go with a basic enum type that implements the interface.
  • 47. Annotation Rules(1)Consistently use the Override annotation check whether override method correctly when complie In an abstract class or an interface, it is worth annotating all methods that you believe to override superclass or superinterface methods. For example, the Set interface adds no new methods to the Collection interface, so it should include Override annotations on all of its method declarations, to ensure that it does not accidentally add any new methods to the Collection interface.
  • 48. AgendaSerialization Creating and Destroying Objects Methods Common to all Objects Classes and Interfaces Generics Methods General Programming Enums and Annotations Concurrency Reflection
  • 49. Synchronize access to shared mutable dataEach thread that reads or writes the data must perform synchronization when multiple threads share mutable data The penalties for failing to synchronize shared mutable data are liveness and safety failures(because rogram behavior can vary radically from one VM to another) volatile modifier is an acceptable form of synchronization for only inter-thread communication and not mutual exclusion
  • 50. Avoid excessive synchronizationDo as little work as possible inside synchronized region Never call an alien method from within a synchronized region to avoid deadlock and data corruption Synchronize your class internally only if there is a good reason to do so, and document your decision clearly
  • 51. Prefer executors and tasks to threadsExecutor Framework in java.util.concurrent ExecutorService executor = Executors.newSingleThreadExecutor(); // submit a runnable for execution executor.execute(runnable); // terminate executor executor.shutdown(); for small program use Executors.newCachedThreadPool for heavily loaded production server use Executors.newFixedThreadPool Unit of work and mechanism are separate two kinds of task: Runnable, Callable
  • 52. Other RulesPrefer concurrency utilities to wait and notify Document thread safety Use lazy inialization judiciously Don't depand on the thread scheduler Avoid thread groups
  • 53. AgendaSerialization Creating and Destroying Objects Methods Common to all Objects Classes and Interfaces Generics Methods General Programming Enums and Annotations Concurrency Reflection
  • 54. What is reflection ?Reflection is commonly used by programs which require the ability to examine or modify the runtime behavior of applications running in the Java virtual machine.
  • 55. Uses of Reflection (1)Extensibility Features An application may make use of external, user-defined classes by creating instances of extensibility objects using their fully-qualified names. Class Browsers and Visual Development Environments A class browser needs to be able to enumerate the members of classes. Visual development environments can benefit from making use of type information available in reflection to aid the developer in writing correct code.
  • 56. Uses of Reflection (2)Debuggers and Test Tools An application may make use of external, user-defined classes by creating instances of extensibility objects using their fully-qualified names.
  • 57. Example (1)get public properties of objectget public static properties of class
  • 58. Example (2)invoke object's methodinvoke static method of class
  • 59. Example (3)new instancedynamic create and access array
  • 60. Get class objectThree ways for general object String str = "reflection"; Class c1=Class.forName("java.lang.String"); Class c2=str.getClass(); Class c3=String.class;Only way for primitive data type and array int.class int[].classThe way for primitive wrapper classes Boolean.TYPE , Byte.TYPE , Character.TYPE , Short.TYPE , Integer.TYPE , Long.TYPE , Floot.TYPE , Double.TYPE , Void.TYPE
  • 61. Drawbacks of Reflection (1)Performance Overhead Because reflection involves types that are dynamically resolved, certain Java virtual machine optimizations can not be performed. Consequently, reflective operations have slower performance than their non-reflective counterparts, and should be avoided in sections of code which are called frequently in performance-sensitive applications. Security Restrictions Reflection requires a runtime permission which may not be present when running under a security manager. This is in an important consideration for code which has to run in a restricted security context, such as in an Applet.
  • 62. Drawbacks of Reflection (2)Exposure of Internals Since reflection allows code to perform operations that would be illegal in non-reflective code, such as accessing private fields and methods, the use of reflection can result in unexpected side-effects, which may render code dysfunctional and may destroy portability. Reflective code breaks abstractions and therefore may change behavior with upgrades of the platform.
  • 63. ReferenceEffective Java, Second Edition, Joshua Bloch The Java™ Programming Language, 3rd Edition, Arnold, Ken, James Gosling, David Holmes. http://java.sun.com/docs/books/tutorial http://java.sun.com/j2se/1.5.0/docs/