SlideShare a Scribd company logo
1 of 45
JAVA BASIC TRAINING
II. The Essentials of Effective Java
Creating and
Destroying Objects
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
“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 Boolean(true);
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
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
NEVER Use Finalizer
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
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) 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
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
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
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
Classes and
 Interfaces
How to Define Java Bean
• What is Java Bean?
  • Data structure
  • Object representative
• The ingredients
  • Fields
  • Setters and Getters
  • Optional equals()/hashCode(), and
    toString()
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
Use Interfaces Only to
     Define Types


• Constant interface pattern
  • Nothing but only constants defined
• Use noninstantiable class instead
Use Interfaces Only to
     Define Types

                                           IT
                                     ER DO
• Constant interface pattern   NEV

  • Nothing but only constants defined
• Use noninstantiable class instead
Use Interfaces Only to
     Define Types

                                           IT
                                     ER DO
• Constant interface pattern   NEV

  • Nothing but only constants defined
• Use noninstantiable class instead
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
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
Exercises

• Try static and non-static member
  class

 • Define the class
 • Instantiate it from outside the
    enclosing class
 • Obtains reference of the enclosing
    instance
Generics
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)
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 nothing
• Check the client code
General
Programming
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
Exceptions
Exception Hierarchy
                                Throwable


                    Exception                       Error


     RuntimeException           ...    VirtualMachineError   ...

NullPointerException                  OutOfMemoryError




              ...                                   ...
Exception Hierarchy
                                Throwable


                    Exception                       Error


     RuntimeException           ...    VirtualMachineError   ...

NullPointerException                  OutOfMemoryError




              ...                                   ...
     Unchecked
Exception Hierarchy
                                Throwable


                    Exception                       Error


     RuntimeException           ...    VirtualMachineError   ...

NullPointerException       Checked    OutOfMemoryError




              ...                                   ...
     Unchecked
Checked and Unchecked

• Checked
 • Required to catch
 • Can reasonably be expected to recover
• Unchecked
 • Not required to catch
 • Generally, not recoverable
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
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
Use Exception Only for
Exceptional 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
Chaining Exceptions
try {
    ...
} catch (AException e) {
    throw new BException(“more description”,   e);
}


• Preserve exception stack trace
• Complete information when exception
  happens

• A bad example is FDSStandardException
Chaining Exceptions
try {
    ...
} catch (AException e) {

}
    throw new BException(“more description”,
                                               e
                                               );




• Preserve exception stack trace
• Complete information when exception
  happens

• A bad example is FDSStandardException
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
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
Exercises

• Define own checked and unchecked
  exceptions
• Write methods throwing the above
  exceptions
• Write client code to invoke the above
  methods
Homework



• Refactor the AddressBook project
  according to what we’ve learned in
  this course

More Related Content

What's hot

Exceptions in Java
Exceptions in JavaExceptions in Java
Exceptions in JavaVadym Lotar
 
Javascript classes and scoping
Javascript classes and scopingJavascript classes and scoping
Javascript classes and scopingPatrick Sheridan
 
Java Pitfalls and Good-to-Knows
Java Pitfalls and Good-to-KnowsJava Pitfalls and Good-to-Knows
Java Pitfalls and Good-to-KnowsMiquel Martin
 
Exception Handling in JAVA
Exception Handling in JAVAException Handling in JAVA
Exception Handling in JAVASURIT DATTA
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overviewBharath K
 
Java Exception Handling
Java Exception HandlingJava Exception Handling
Java Exception HandlingDeeptiJava
 
Exception handling
Exception handlingException handling
Exception handlingRavi Sharda
 

What's hot (13)

Exceptions in Java
Exceptions in JavaExceptions in Java
Exceptions in Java
 
Javascript classes and scoping
Javascript classes and scopingJavascript classes and scoping
Javascript classes and scoping
 
Ruby basics
Ruby basicsRuby basics
Ruby basics
 
Java Pitfalls and Good-to-Knows
Java Pitfalls and Good-to-KnowsJava Pitfalls and Good-to-Knows
Java Pitfalls and Good-to-Knows
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Exception Handling in JAVA
Exception Handling in JAVAException Handling in JAVA
Exception Handling in JAVA
 
Java
JavaJava
Java
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Built in exceptions
Built in exceptions Built in exceptions
Built in exceptions
 
Java Exception Handling
Java Exception HandlingJava Exception Handling
Java Exception Handling
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception hierarchy
Exception hierarchyException hierarchy
Exception hierarchy
 

Similar to 2 the essentials of effective java

Similar to 2 the essentials of effective java (20)

Exceptions.pptx
Exceptions.pptxExceptions.pptx
Exceptions.pptx
 
Exception handling in .net
Exception handling in .netException handling in .net
Exception handling in .net
 
Jvm2
Jvm2Jvm2
Jvm2
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
ACP - Week - 9.pptx
ACP - Week - 9.pptxACP - Week - 9.pptx
ACP - Week - 9.pptx
 
Training material exceptions v1
Training material   exceptions v1Training material   exceptions v1
Training material exceptions v1
 
Exception handling in ASP .NET
Exception handling in ASP .NETException handling in ASP .NET
Exception handling in ASP .NET
 
Java chapter 6
Java chapter 6Java chapter 6
Java chapter 6
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
A36519192_21789_4_2018_Exception Handling.ppt
A36519192_21789_4_2018_Exception Handling.pptA36519192_21789_4_2018_Exception Handling.ppt
A36519192_21789_4_2018_Exception Handling.ppt
 
L14 exception handling
L14 exception handlingL14 exception handling
L14 exception handling
 
Exception handling
Exception handlingException handling
Exception handling
 
Developer testing 201: When to Mock and When to Integrate
Developer testing 201: When to Mock and When to IntegrateDeveloper testing 201: When to Mock and When to Integrate
Developer testing 201: When to Mock and When to Integrate
 

Recently uploaded

The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesKari Kakkonen
 
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security ObservabilityGlenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security Observabilityitnewsafrica
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality AssuranceInflectra
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfpanagenda
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Nikki Chapple
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityIES VE
 
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...itnewsafrica
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterMydbops
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integrationmarketing932765
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentPim van der Noll
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfNeo4j
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 
Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024TopCSSGallery
 

Recently uploaded (20)

The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examples
 
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security ObservabilityGlenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a reality
 
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL Router
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdf
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 
Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024
 

2 the essentials of effective java

  • 1. JAVA BASIC TRAINING II. The Essentials of Effective Java
  • 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. “withXxx” Pattern • Consider a class with many fields • Initialize with setters • “withXxx” pattern
  • 5. Avoid Creating Unnecessary Objects • String str = new String(“hello”); • Integer i = new Integer(10); • Boolean b = new Boolean(true);
  • 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. 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
  • 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. Methods Common to All Objects
  • 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. 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. 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. 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
  • 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. 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. Use Interfaces Only to Define Types • Constant interface pattern • Nothing but only constants defined • Use noninstantiable class instead
  • 19. Use Interfaces Only to Define Types IT ER DO • Constant interface pattern NEV • Nothing but only constants defined • Use noninstantiable class instead
  • 20. Use Interfaces Only to Define Types IT ER DO • Constant interface pattern NEV • Nothing but only constants defined • Use noninstantiable class instead
  • 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. 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
  • 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
  • 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. Exercises • SuppressWarnings annotation for unchecked access • Write a generic method
  • 28. Methods • Return empty arrays or collections, instead of null • Write javadoc comments for all exposed API elements
  • 29. Exercises • Write a method returning null representing nothing • Write a method returning empty collection representing nothing • Check the client code
  • 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
  • 33. Exception Hierarchy Throwable Exception Error RuntimeException ... VirtualMachineError ... NullPointerException OutOfMemoryError ... ...
  • 34. Exception Hierarchy Throwable Exception Error RuntimeException ... VirtualMachineError ... NullPointerException OutOfMemoryError ... ... Unchecked
  • 35. Exception Hierarchy Throwable Exception Error RuntimeException ... VirtualMachineError ... NullPointerException Checked OutOfMemoryError ... ... Unchecked
  • 36. Checked and Unchecked • Checked • Required to catch • Can reasonably be expected to recover • Unchecked • Not required to catch • Generally, not recoverable
  • 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. 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. Use Exception Only for Exceptional 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. Chaining Exceptions try { ... } catch (AException e) { throw new BException(“more description”, e); } • Preserve exception stack trace • Complete information when exception happens • A bad example is FDSStandardException
  • 41. Chaining Exceptions try { ... } catch (AException e) { } throw new BException(“more description”, e ); • Preserve exception stack trace • Complete information when exception happens • A bad example is FDSStandardException
  • 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. 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. Exercises • Define own checked and unchecked exceptions • Write methods throwing the above exceptions • Write client code to invoke the above methods
  • 45. Homework • Refactor the AddressBook project according to what we’ve learned in this course

Editor's Notes

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. \n
  32. \n
  33. \n
  34. \n
  35. \n
  36. \n
  37. \n
  38. \n
  39. \n
  40. \n
  41. \n
  42. \n
  43. \n