2 the essentials of effective java
-
Upload
honnix-liang -
Category
Technology
-
view
757 -
download
1
Transcript of 2 the essentials of effective java
![Page 1: 2 the essentials of effective java](https://reader034.fdocuments.us/reader034/viewer/2022051721/555c3d64d8b42a2c068b4b31/html5/thumbnails/1.jpg)
JAVA BASIC TRAININGII. The Essentials of Effective Java
![Page 2: 2 the essentials of effective java](https://reader034.fdocuments.us/reader034/viewer/2022051721/555c3d64d8b42a2c068b4b31/html5/thumbnails/2.jpg)
Creating and Destroying Objects
![Page 3: 2 the essentials of effective java](https://reader034.fdocuments.us/reader034/viewer/2022051721/555c3d64d8b42a2c068b4b31/html5/thumbnails/3.jpg)
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
![Page 4: 2 the essentials of effective java](https://reader034.fdocuments.us/reader034/viewer/2022051721/555c3d64d8b42a2c068b4b31/html5/thumbnails/4.jpg)
“withXxx” Pattern
• Consider a class with many fields
• Initialize with setters
• “withXxx” pattern
![Page 5: 2 the essentials of effective java](https://reader034.fdocuments.us/reader034/viewer/2022051721/555c3d64d8b42a2c068b4b31/html5/thumbnails/5.jpg)
Avoid Creating Unnecessary Objects
• String str = new String(“hello”);
• Integer i = new Integer(10);
• Boolean b = new Boolean(true);
![Page 6: 2 the essentials of effective java](https://reader034.fdocuments.us/reader034/viewer/2022051721/555c3d64d8b42a2c068b4b31/html5/thumbnails/6.jpg)
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
![Page 7: 2 the essentials of effective java](https://reader034.fdocuments.us/reader034/viewer/2022051721/555c3d64d8b42a2c068b4b31/html5/thumbnails/7.jpg)
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
![Page 8: 2 the essentials of effective java](https://reader034.fdocuments.us/reader034/viewer/2022051721/555c3d64d8b42a2c068b4b31/html5/thumbnails/8.jpg)
NEVER Use Finalizer
![Page 9: 2 the essentials of effective java](https://reader034.fdocuments.us/reader034/viewer/2022051721/555c3d64d8b42a2c068b4b31/html5/thumbnails/9.jpg)
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
![Page 10: 2 the essentials of effective java](https://reader034.fdocuments.us/reader034/viewer/2022051721/555c3d64d8b42a2c068b4b31/html5/thumbnails/10.jpg)
Methods Common to All Objects
![Page 11: 2 the essentials of effective java](https://reader034.fdocuments.us/reader034/viewer/2022051721/555c3d64d8b42a2c068b4b31/html5/thumbnails/11.jpg)
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
![Page 12: 2 the essentials of effective java](https://reader034.fdocuments.us/reader034/viewer/2022051721/555c3d64d8b42a2c068b4b31/html5/thumbnails/12.jpg)
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
![Page 13: 2 the essentials of effective java](https://reader034.fdocuments.us/reader034/viewer/2022051721/555c3d64d8b42a2c068b4b31/html5/thumbnails/13.jpg)
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
![Page 14: 2 the essentials of effective java](https://reader034.fdocuments.us/reader034/viewer/2022051721/555c3d64d8b42a2c068b4b31/html5/thumbnails/14.jpg)
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
![Page 15: 2 the essentials of effective java](https://reader034.fdocuments.us/reader034/viewer/2022051721/555c3d64d8b42a2c068b4b31/html5/thumbnails/15.jpg)
Classes and Interfaces
![Page 16: 2 the essentials of effective java](https://reader034.fdocuments.us/reader034/viewer/2022051721/555c3d64d8b42a2c068b4b31/html5/thumbnails/16.jpg)
How to Define Java Bean
• What is Java Bean?
• Data structure
• Object representative
• The ingredients
• Fields
• Setters and Getters
• Optional equals()/hashCode(), and toString()
![Page 17: 2 the essentials of effective java](https://reader034.fdocuments.us/reader034/viewer/2022051721/555c3d64d8b42a2c068b4b31/html5/thumbnails/17.jpg)
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
![Page 18: 2 the essentials of effective java](https://reader034.fdocuments.us/reader034/viewer/2022051721/555c3d64d8b42a2c068b4b31/html5/thumbnails/18.jpg)
Use Interfaces Only to Define Types
• Constant interface pattern
• Nothing but only constants defined
• Use noninstantiable class instead
![Page 19: 2 the essentials of effective java](https://reader034.fdocuments.us/reader034/viewer/2022051721/555c3d64d8b42a2c068b4b31/html5/thumbnails/19.jpg)
Use Interfaces Only to Define Types
• Constant interface pattern
• Nothing but only constants defined
• Use noninstantiable class instead
NEVER DO IT
![Page 20: 2 the essentials of effective java](https://reader034.fdocuments.us/reader034/viewer/2022051721/555c3d64d8b42a2c068b4b31/html5/thumbnails/20.jpg)
Use Interfaces Only to Define Types
• Constant interface pattern
• Nothing but only constants defined
• Use noninstantiable class instead
NEVER DO IT
![Page 21: 2 the essentials of effective java](https://reader034.fdocuments.us/reader034/viewer/2022051721/555c3d64d8b42a2c068b4b31/html5/thumbnails/21.jpg)
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
![Page 22: 2 the essentials of effective java](https://reader034.fdocuments.us/reader034/viewer/2022051721/555c3d64d8b42a2c068b4b31/html5/thumbnails/22.jpg)
Favor Static Member Classes 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
![Page 23: 2 the essentials of effective java](https://reader034.fdocuments.us/reader034/viewer/2022051721/555c3d64d8b42a2c068b4b31/html5/thumbnails/23.jpg)
Exercises
• Try static and non-static member class
• Define the class
• Instantiate it from outside the enclosing class
• Obtains reference of the enclosing instance
![Page 24: 2 the essentials of effective java](https://reader034.fdocuments.us/reader034/viewer/2022051721/555c3d64d8b42a2c068b4b31/html5/thumbnails/24.jpg)
Generics
![Page 25: 2 the essentials of effective java](https://reader034.fdocuments.us/reader034/viewer/2022051721/555c3d64d8b42a2c068b4b31/html5/thumbnails/25.jpg)
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)
![Page 26: 2 the essentials of effective java](https://reader034.fdocuments.us/reader034/viewer/2022051721/555c3d64d8b42a2c068b4b31/html5/thumbnails/26.jpg)
Exercises
• SuppressWarnings annotation for unchecked access
• Write a generic method
![Page 27: 2 the essentials of effective java](https://reader034.fdocuments.us/reader034/viewer/2022051721/555c3d64d8b42a2c068b4b31/html5/thumbnails/27.jpg)
Methods
![Page 28: 2 the essentials of effective java](https://reader034.fdocuments.us/reader034/viewer/2022051721/555c3d64d8b42a2c068b4b31/html5/thumbnails/28.jpg)
Methods
• Return empty arrays or collections, instead of null
• Write javadoc comments for all exposed API elements
![Page 29: 2 the essentials of effective java](https://reader034.fdocuments.us/reader034/viewer/2022051721/555c3d64d8b42a2c068b4b31/html5/thumbnails/29.jpg)
Exercises
• Write a method returning null representing nothing
• Write a method returning empty collection representing nothing
• Check the client code
![Page 30: 2 the essentials of effective java](https://reader034.fdocuments.us/reader034/viewer/2022051721/555c3d64d8b42a2c068b4b31/html5/thumbnails/30.jpg)
General Programming
![Page 31: 2 the essentials of effective java](https://reader034.fdocuments.us/reader034/viewer/2022051721/555c3d64d8b42a2c068b4b31/html5/thumbnails/31.jpg)
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
![Page 32: 2 the essentials of effective java](https://reader034.fdocuments.us/reader034/viewer/2022051721/555c3d64d8b42a2c068b4b31/html5/thumbnails/32.jpg)
Exceptions
![Page 33: 2 the essentials of effective java](https://reader034.fdocuments.us/reader034/viewer/2022051721/555c3d64d8b42a2c068b4b31/html5/thumbnails/33.jpg)
...
Exception Hierarchy
Exception
RuntimeException
Throwable
Error
VirtualMachineError ...
OutOfMemoryErrorNullPointerException
...
...
![Page 34: 2 the essentials of effective java](https://reader034.fdocuments.us/reader034/viewer/2022051721/555c3d64d8b42a2c068b4b31/html5/thumbnails/34.jpg)
...
Exception Hierarchy
Exception
RuntimeException
Throwable
Error
VirtualMachineError ...
OutOfMemoryErrorNullPointerException
...
Unchecked
...
![Page 35: 2 the essentials of effective java](https://reader034.fdocuments.us/reader034/viewer/2022051721/555c3d64d8b42a2c068b4b31/html5/thumbnails/35.jpg)
...
Exception Hierarchy
Exception
RuntimeException
Throwable
Error
VirtualMachineError ...
OutOfMemoryErrorNullPointerException
...
Unchecked
...
Checked
![Page 36: 2 the essentials of effective java](https://reader034.fdocuments.us/reader034/viewer/2022051721/555c3d64d8b42a2c068b4b31/html5/thumbnails/36.jpg)
Checked and Unchecked
• Checked
• Required to catch
• Can reasonably be expected to recover
• Unchecked
• Not required to catch
• Generally, not recoverable
![Page 37: 2 the essentials of effective java](https://reader034.fdocuments.us/reader034/viewer/2022051721/555c3d64d8b42a2c068b4b31/html5/thumbnails/37.jpg)
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
![Page 38: 2 the essentials of effective java](https://reader034.fdocuments.us/reader034/viewer/2022051721/555c3d64d8b42a2c068b4b31/html5/thumbnails/38.jpg)
Favor Standard Exceptions
• Before go creating your own exception type, favor standard exception
• Java platform libraries provide a basic set of unchecked exceptions
Exception Occasion for UseIllegalArgumentException null value is not good to go
IllegalStatementException instance state is not OK for method invocation
NullPointerException null value is not prohibited
IndexOutOfBoundsException input parameter is out of range
ConcurrentModificationException concurrent modification of an object has been detected where it is prohibited
UnsupportedOperationException object does not support method
![Page 39: 2 the essentials of effective java](https://reader034.fdocuments.us/reader034/viewer/2022051721/555c3d64d8b42a2c068b4b31/html5/thumbnails/39.jpg)
Use Exception Only for Exceptional Conditionstry { 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
![Page 40: 2 the essentials of effective java](https://reader034.fdocuments.us/reader034/viewer/2022051721/555c3d64d8b42a2c068b4b31/html5/thumbnails/40.jpg)
Chaining Exceptionstry { ...} catch (AException e) { throw new BException(“more description”, );}
• Preserve exception stack trace
• Complete information when exception happens
• A bad example is FDSStandardException
e
![Page 41: 2 the essentials of effective java](https://reader034.fdocuments.us/reader034/viewer/2022051721/555c3d64d8b42a2c068b4b31/html5/thumbnails/41.jpg)
Chaining Exceptionstry { ...} catch (AException e) { throw new BException(“more description”, );}
• Preserve exception stack trace
• Complete information when exception happens
• A bad example is FDSStandardException
e
![Page 42: 2 the essentials of effective java](https://reader034.fdocuments.us/reader034/viewer/2022051721/555c3d64d8b42a2c068b4b31/html5/thumbnails/42.jpg)
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
![Page 43: 2 the essentials of effective java](https://reader034.fdocuments.us/reader034/viewer/2022051721/555c3d64d8b42a2c068b4b31/html5/thumbnails/43.jpg)
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
![Page 44: 2 the essentials of effective java](https://reader034.fdocuments.us/reader034/viewer/2022051721/555c3d64d8b42a2c068b4b31/html5/thumbnails/44.jpg)
Exercises
• Define own checked and unchecked exceptions
• Write methods throwing the above exceptions
• Write client code to invoke the above methods
![Page 45: 2 the essentials of effective java](https://reader034.fdocuments.us/reader034/viewer/2022051721/555c3d64d8b42a2c068b4b31/html5/thumbnails/45.jpg)
Homework
• Refactor the AddressBook project according to what we’ve learned in this course