More Effective Programming With Java Technology Joshua Bloch Senior Staff Engineer Sun Microsystems Java Software Session 2502 Presentation Goal Learn to use the Java programming language and its libraries more effectively 2 Session 2502 View From 10 000 feet This talk consists of Patterns and idioms to emulate Pitfalls to avoid Excerpted from Effective Java Programming Language Guide Addison Wesley June 2001 3 Session 2502 Speaker s Qualifications Author Effective Java Programming Language Guide Addison Wesley June 2001 Architect 4 Java Collections Framework java math java util prefs the assert construct Chained exceptions StackTraceElement ThreadLocal Timer etc Session 2502 Topics Covered in the Book The language Libraries java lang java util java io Not covered GUI Programming Enterprise APIs Ten chapters fifty seven items 5 Session 2502 Topics Covered in the Talk I Duplicate Object Creation Item 4 6 II Defensive Copying Item 24 III Immutable Classes Item 13 Session 2502 I Avoid Duplicate Object Creation Reuse existing object instead Simplest example String s new String DON T DO THIS String s Do this instead In loops savings can be substantial 7 Session 2502 Another Example public class Person private final Date birthDate Other fields omitted public Person Date birthDate this birthDate birthDate UNNECESSARY OBJECT CREATION DON T DO THIS public boolean isBabyBoomer Calendar gmtCal Calendar getInstance TimeZone getTimeZone GMT gmtCal set 1946 Calendar JANUARY 1 0 0 0 Date boomStart gmtCal getTime gmtCal set 1965 Calendar JANUARY 1 0 0 0 Date boomEnd gmtCal getTime return birthDate compareTo boomStart 0 birthDate compareTo boomEnd 0 8 Session 2502 Another Example Cont Do This Instead Clearer and faster private static final Date BOOM START private static final Date BOOM END static Calendar gmtCal Calendar getInstance TimeZone getTimeZone GMT gmtCal set 1946 Calendar JANUARY 1 0 0 0 BOOM START gmtCal getTime gmtCal set 1965 Calendar JANUARY 1 0 0 0 BOOM END gmtCal getTime public boolean isBabyBoomer 100 times faster return birthDate compareTo BOOM START 0 birthDate compareTo BOOM END 0 9 Session 2502 Summary Don t create unnecessary duplicate objects Reuse improves clarity and performance But don t be afraid to create objects Object creation is cheap on modern Vms Can enhance simplicity power robustness 10 Session 2502 II Defensive Copying Unlike C C Java programming language safe Immune to buffer overruns wild pointers etc Makes it possible to write robust classes Correctness doesn t depend on other modules Even in safe language requires effort 11 Session 2502 Defensive Programming Assume clients will try to destroy invariants May actually be true More likely honest mistakes Ensure class invariants survive any inputs 12 Session 2502 This Class Is Not Robust public final class Period private final Date start end Invariant start end throws IllegalArgumentException if start end throws NullPointerException if start or end is null public Period Date start Date end if start compareTo end 0 throw new IllegalArgumentException start end this start start this end end public Date start return start public Date end return end Remainder omitted 13 Session 2502 The Problem Date Is Mutable Attack the internals of a Period instance Date start new Date The current time Date end new Date Period p new Period start end end setYear 78 Modifies internals of p 14 Session 2502 The Solution Defensive Copying Repaired constructor defensively copies parameters public Period Date start Date end this start new Date start getTime this end new Date end getTime if this start compareTo this end 0 throw new IllegalArgumentException start end 15 Session 2502 An Important Detail Copies made before checking parameters Validity check performed on copies Eliminate window of vulnerability between parameter check and copy Thwarts multithreaded attack BROKEN Permits multithreaded attack public Period Date start Date end if start compareTo end 0 throw new IllegalArgumentException start end Window of vulnerability this start new Date start getTime this end new Date end getTime 16 Session 2502 Another Important Detail Used constructor not clone to make copies Necessary because Date class is nonfinal Attacker could implement malicious subclass Records reference to each instance in list Provides attacker with access to instance list 17 Session 2502 Unfortunately Constructors Are Only Half the Battle Accessor attack on internals of Period Date start new Date Date end new Date Period p new Period start end p end setYear 78 Modifies internals of p 18 Session 2502 The Solution More Defensive Copying Repaired accessors defensively copy fields public Date start return Date start clone clone OK public Date end return Date end clone Now Period class is robust 19 Session 2502 Summary Don t incorporate mutable parameters into object make defensive copies Constructors static factories pseudo constructors mutators Return defensive copies of mutable fields Accessors Real lesson use immutable components Eliminates the need for defensive copying 20 Session 2502 III Immutable Classes Class whose instances cannot be modified Examples String Integer BigInteger How why and when to use them 21 Session 2502 How to Write an Immutable Class Don t provide any mutators Ensure that no methods may be overridden Make all fields final Make all fields private Ensure exclusive access to any mutable components 22 Session 2502 Example public final class Complex private final float re im public Complex float re float im this re re this im im Accessors without corresponding mutators public float realPart return re public float imaginaryPart return im subtract multiply divide similar to add public Complex add Complex c return new Complex re c re im c im 23 Session 2502 Example Cont public boolean equals Object o if o this return true if o instanceof Complex return false Complex c Complex o return Float floatToIntBits re Float floatToIntBits c re Float floatToIntBits im Float floatToIntBits c im public int hashCode int result 17 Float floatToIntBits re result 37 result Float floatToIntBits im return result public String toString return re im i 24 Session 2502 Distinguishing Characteristic Return new instance instead of modifying Functional programming May seem unnatural at first Many advantages 25 Session 2502 Advantage 1 Simplicity Instances have exactly one state Easy to design implement Constructors establish invariants Invariants can never be corrupted
View Full Document
Unlocking...