JAVA BASIC TRAININGII. The Essentials of Effective Java
Creating andDestroying Objects
Good Ways to Define          Class• Class Modifier   • Should it be final• Default Constructor   • Compiler generates one if...
“withXxx” Pattern• Consider a class with many fields• Initialize with setters• “withXxx” pattern
Avoid Creating  Unnecessary Objects• String str = new String(“hello”);• Integer i = new Integer(10);• Boolean b = new Bool...
Avoid Creating  Unnecessary Objects• String str = new String(“hello”);• Integer i = new Integer(10);• Boolean b = new Bool...
Memory Leak• Garbage Collection  • Mark-Sweep-Compact, as an example• Memory Leak in Java means unintentionally  retained•...
NEVER Use Finalizer
Exercises• Refine Resource/Designer/Tester • name, age, id, gender, unit as fields• Static class ResourceBuilder • Which can...
Methods Common to    All Objects
equals()• Suppose x, y, z are all non-null references• Reflexive  • x.equals(x) must return true• Symmetric  • x.equals(y) ...
hashCode()• Equal objects must have equal hash  codes• If equals() is overridden,  hashCode() must be overridden• Failed t...
toString()• Default toString returns something like  “Designer@163b91”• A good toString() implementation  • Makes the clas...
Exercises• Add equals() and hashCode() to  Designer and Tester • Consider about how to write a “correct”    equals() and “...
Classes and Interfaces
How to Define Java Bean• What is Java Bean?  • Data structure  • Object representative• The ingredients  • Fields  • Setter...
Prefer Interface to         Abstract Class• No multiple inheritance in Java• Pros  • Easily retrofitted to implement a new ...
Use Interfaces Only to     Define Types• Constant interface pattern  • Nothing but only constants defined• Use noninstantiab...
Use Interfaces Only to     Define Types                                           IT                                     ER...
Use Interfaces Only to     Define Types                                           IT                                     ER...
Prefer Class Hierarchies   to Tagged Classes• What is tagged class?  • A class with certain field to indicate    the actual...
Favor Static MemberClasses over Non-static• The class defined in another class• Non-static member class can  • Obtain refer...
Exercises• Try static and non-static member  class • Define the class • Instantiate it from outside the    enclosing class ...
Generics
Generics• Don’t use raw types in new code• Favor generic types • List<String>, instead of List• Favor generic method • Lis...
Exercises• SuppressWarnings annotation for  unchecked access• Write a generic method
Methods
Methods• Return empty arrays or collections,  instead of null• Write javadoc comments for all  exposed API elements
Exercises• Write a method returning null  representing nothing• Write a method returning empty  collection representing no...
GeneralProgramming
General Programming• Minimize the scope of local variables• Mark variable as final whenever possible• Prefer for-each loop•...
Exceptions
Exception Hierarchy                                Throwable                    Exception                       Error     ...
Exception Hierarchy                                Throwable                    Exception                       Error     ...
Exception Hierarchy                                Throwable                    Exception                       Error     ...
Checked and Unchecked• Checked • Required to catch • Can reasonably be expected to recover• Unchecked • Not required to ca...
Avoid Unnecessary of   Checked Exception• Checked exception is great  • Forcing programmer to deal with exception  • Enhan...
Favor Standard                  Exceptions                                    Exception                     Occasion for U...
Use Exception Only forExceptional Conditions try {     int i = 0;     while (true) {         range[i++].climb();     } } c...
Chaining Exceptionstry {    ...} catch (AException e) {    throw new BException(“more description”,   e);}• Preserve excep...
Chaining Exceptionstry {    ...} catch (AException e) {}    throw new BException(“more description”,                      ...
How to Define Own        Exception• Extend from Exception or RuntimeException• Provide serialVersionUID• Override all const...
Other Best Practice• Document all exceptions thrown by each  method• Always set detail message• Don’t catch and ignore exc...
Exercises• Define own checked and unchecked  exceptions• Write methods throwing the above  exceptions• Write client code to...
Homework• Refactor the AddressBook project  according to what we’ve learned in  this course
Upcoming SlideShare
Loading in …5
×

2 the essentials of effective java

745 views

Published on

a series of basic java training courses, this is the second one

Published in: Technology, Education
  • Be the first to comment

2 the essentials of effective java

  1. 1. JAVA BASIC TRAININGII. The Essentials of Effective Java
  2. 2. Creating andDestroying Objects
  3. 3. Good Ways to Define Class• Class Modifier • Should it be final• Default Constructor • Compiler generates one if not defined • But, always define it explicitly• Always invoke super() explicitly• Visibility • Class • Constructor• Singleton
  4. 4. “withXxx” Pattern• Consider a class with many fields• Initialize with setters• “withXxx” pattern
  5. 5. Avoid Creating Unnecessary Objects• String str = new String(“hello”);• Integer i = new Integer(10);• Boolean b = new Boolean(true);
  6. 6. Avoid Creating Unnecessary Objects• String str = new String(“hello”);• Integer i = new Integer(10);• Boolean b = new Boolean(true); do not waste time and memory
  7. 7. Memory Leak• Garbage Collection • Mark-Sweep-Compact, as an example• Memory Leak in Java means unintentionally retained• Nulling out references when really necessary • It should be the exceptional rather than the normal • The best way is let the variable fall out of scope
  8. 8. NEVER Use Finalizer
  9. 9. Exercises• Refine Resource/Designer/Tester • name, age, id, gender, unit as fields• Static class ResourceBuilder • Which can build a kind of resource• Manager as a Singleton• Create memory leak
  10. 10. Methods Common to All Objects
  11. 11. equals()• Suppose x, y, z are all non-null references• Reflexive • x.equals(x) must return true• Symmetric • x.equals(y) must return true if and only if y.equals(x)returns true• Transitive • if x.equals(y) returns true • and y.equals(z) returns true • then x.equals(z) must return true• Consistent • x.equals(y) must consistently return the same result
  12. 12. hashCode()• Equal objects must have equal hash codes• If equals() is overridden, hashCode() must be overridden• Failed to do so, there will be trouble working with hash-based collections
  13. 13. toString()• Default toString returns something like “Designer@163b91”• A good toString() implementation • Makes the class pleasant to use • Should return all interesting information contained in the object • Specifies the format if necessary and stick to it • Provides programmatic access to the returned string if necessary
  14. 14. Exercises• Add equals() and hashCode() to Designer and Tester • Consider about how to write a “correct” equals() and “perfect” hashCode()• Add toString() to Designer and Tester • A parse() method in Resource to parse a Designer or Tester
  15. 15. Classes and Interfaces
  16. 16. How to Define Java Bean• What is Java Bean? • Data structure • Object representative• The ingredients • Fields • Setters and Getters • Optional equals()/hashCode(), and toString()
  17. 17. Prefer Interface to Abstract Class• No multiple inheritance in Java• Pros • Easily retrofitted to implement a new interface • Ideal for defining mixins: Comparable for example • Allow construction of nonhierarchical type framework: someone can be both a singer and songwriter• Cons • Not off-the-shelf to use • Once released and widely implemented, almost impossible to change• Skeletal implementation combining interface and abstract class • Map/AbstractMap • Set/AbstractSet
  18. 18. Use Interfaces Only to Define Types• Constant interface pattern • Nothing but only constants defined• Use noninstantiable class instead
  19. 19. Use Interfaces Only to Define Types IT ER DO• Constant interface pattern NEV • Nothing but only constants defined• Use noninstantiable class instead
  20. 20. Use Interfaces Only to Define Types IT ER DO• Constant interface pattern NEV • Nothing but only constants defined• Use noninstantiable class instead
  21. 21. Prefer Class Hierarchies to Tagged Classes• What is tagged class? • A class with certain field to indicate the actual type• Tagged class are verbose, error-prone, and inefficient• Unfortunately, tagged class is not OO
  22. 22. Favor Static MemberClasses over Non-static• The class defined in another class• Non-static member class can • Obtain reference to the enclosing instance using the qualified this construct• Static member class can • Be instantiated in isolation from an instance of its enclosing class• Make it a static member class • Whenever it does not require access to an enclosing instance • When it should be instantiated from outside of the enclosing class • Get rid of time and space costs to store reference to its enclosing instance
  23. 23. Exercises• Try static and non-static member class • Define the class • Instantiate it from outside the enclosing class • Obtains reference of the enclosing instance
  24. 24. Generics
  25. 25. Generics• Don’t use raw types in new code• Favor generic types • List<String>, instead of List• Favor generic method • List<T> hello(T word), instead of List<Object> hello(Object word)
  26. 26. Exercises• SuppressWarnings annotation for unchecked access• Write a generic method
  27. 27. Methods
  28. 28. Methods• Return empty arrays or collections, instead of null• Write javadoc comments for all exposed API elements
  29. 29. Exercises• Write a method returning null representing nothing• Write a method returning empty collection representing nothing• Check the client code
  30. 30. GeneralProgramming
  31. 31. General Programming• Minimize the scope of local variables• Mark variable as final whenever possible• Prefer for-each loop• Know and use the libraries• String concatenation, StringBuilder and StringBuffer• Refer to object by interface
  32. 32. Exceptions
  33. 33. Exception Hierarchy Throwable Exception Error RuntimeException ... VirtualMachineError ...NullPointerException OutOfMemoryError ... ...
  34. 34. Exception Hierarchy Throwable Exception Error RuntimeException ... VirtualMachineError ...NullPointerException OutOfMemoryError ... ... Unchecked
  35. 35. Exception Hierarchy Throwable Exception Error RuntimeException ... VirtualMachineError ...NullPointerException Checked OutOfMemoryError ... ... Unchecked
  36. 36. Checked and Unchecked• Checked • Required to catch • Can reasonably be expected to recover• Unchecked • Not required to catch • Generally, not recoverable
  37. 37. Avoid Unnecessary of Checked Exception• Checked exception is great • Forcing programmer to deal with exception • Enhancing reliability• Overusing it will make API less pleasant to use• If contract can be made between API and client, no need to use checked exception • For example, wrong format of argument • A method provided to check exceptional condition
  38. 38. Favor Standard Exceptions Exception Occasion for Use IllegalArgumentException null value is not good to go• Before go creating your own exception type, favor IllegalStatementException instance state is not OK for method invocation standard exception NullPointerException null value is not prohibited• Java platform libraries provide a basic set of IndexOutOfBoundsException input parameter is out of range unchecked exceptions concurrent modification of an object ConcurrentModificationException has been detected where it is prohibited UnsupportedOperationException object does not support method
  39. 39. Use Exception Only forExceptional Conditions try { int i = 0; while (true) { range[i++].climb(); } } catch (ArrayIndexOutOfBoundsException e) { ... }• Exception should only be used for exceptional conditions• Well designed API must not force its clients to use exception for ordinary control flow
  40. 40. Chaining Exceptionstry { ...} catch (AException e) { throw new BException(“more description”, e);}• Preserve exception stack trace• Complete information when exception happens• A bad example is FDSStandardException
  41. 41. Chaining Exceptionstry { ...} catch (AException e) {} throw new BException(“more description”, e );• Preserve exception stack trace• Complete information when exception happens• A bad example is FDSStandardException
  42. 42. How to Define Own Exception• Extend from Exception or RuntimeException• Provide serialVersionUID• Override all constructors • Default • With detail message only • With detail message and cause • With cause only• Add you own fields if necessary, for example error code
  43. 43. Other Best Practice• Document all exceptions thrown by each method• Always set detail message• Don’t catch and ignore exception, at least write down a comment
  44. 44. Exercises• Define own checked and unchecked exceptions• Write methods throwing the above exceptions• Write client code to invoke the above methods
  45. 45. Homework• Refactor the AddressBook project according to what we’ve learned in this course

×