SlideShare a Scribd company logo
Creating & Destroying Objects
Reference: Effective Java - Joshua Bloch
-Rohit Vaidya
Agenda
● Discuss over object creation and destruction
● Study best practices
● Use profiler to go over how good or bad code
is
Items
● Item1 Consider Static factory methods
● Item2 Consider builders
● Item3 Enforce Singleton,private constructors or
enum type
● Item4 Enforce non-instanstiability private
constructors
● Item5 Avoid creating unnecessary Objects
● Item6 Avoid finalizers
Creating Objects
● When and how to create Objects
● How to avoid creating them
● Ensure they are destroyed
● Cleanup before destruction
Item 1
Consider static factory methods instead of
constructors
Item 1 Premise
● Create an object
● Implicitly not create objects when unnecessary
● Ability to create a object of subtype
Item1 - Solution
● Provide static factory methods
● Advantages
– Unlike constructors they have names
– Not required each time you create a new object
● E.g: Boolean.valueof(boolean) – never creates a object
– Can return a object of any subtype of return type
● Disadvantages
– Classes without public or protected members cannot be sub classed
● This has a hidden advantage
– Not easily distinguishable from other static factory methods
Item 2
Consider builder when faced with many
constructor parameter
Item 2 Premise
● Many parameter constructors or static factories do
not scale
– Hell for the client
● Telescoping constructor pattern
– Why its bad? Hard to read/write code
● Java Beans pattern
– Inconsistent path way through its construction
– Does not allow your class to be immutable. Setters!!!
Item 2 Solution
● Builders!!!
– Makes your class immutable. Important
– Makes it easy to read and write code
– Builders allows you to set invariants. If Invariant is not
satisfied throw IllegalArgumentException
– Builders can have multiple varargs where as constructor
only one
● “The Builder pattern is a good choice when designing
classes whose constructors or static factories would
have more than a handful of parameters"
Item 3
Enforce the singleton property with a private
constructor or an enum Type
Item 3 - Premise
● Make a class singleton
● Avoid reflection attacks on singleton classes
made singleton conventionally
– AccessibleObject.setAccessible
● Serialization making multiple copies of the
same object
Item3-Solution
● Have a public static final field which contains the instance
– Class declaration makes it evident, its singleton
● Have a private static field with the factory method returning the instance
– The factory API can be easily modified to make it non singleton
● Use enum to create singletons
● Have the constructor throw an exception – to solve Reflection problem
● Make all the field transient and implement a resolveObject API to resolve
serialization problem
Item 4
Enforce non-instantiability with a private
constructor
Item 4 – Premise
● Want to write a class which is a group of static
methods
● Write group of methods on primitive values or
arrays. e.g: java.util.Arrays java.lang.Math
● Don't create an object where its non-sensical
to do so – Utility Classes
Item 4 - Solution
● Simple: Add a private constructor.
● If you don't? - A default constructor gets
generated. You can still do a
X obj = new X(); //This is bad.
● You have instantiated a class when not
required
● Positive Side Effect: Can't be subclasses
Item 5
Avoid creating unnecessary Objects
Premise
● Reuse objects
● Consequently avoid creating new instances
● Reuse immutable objects and mutable objects
● Avoid accidentally creating objects
Solution
● String pool of-course!!!
– String s = new String(“string”);//Code smell
● Use static factory methods for object creation
– Boolean(String) //Code smell
● Reuse Mutable Objects. Assuming these objects
are not expected to be mutated
● Safe to reuse immutable objects
● Beware of auto-boxing
Item 5 - Snippets
Item5 - Profiling
Item5 - Profiling
Item 5 – Fix it
Item 5 After Fix
Item 5 – After fix
Item 6
Eliminate Obsolete References
Premise
● Need to understand Memory Leaks first
● Don't misunderstand Java Garbage collector cleans
it all
– Obsolete References to blame.
– References that will never be referenced again
● Memory Leaks in caches
● Listeners and their callbacks, another culprit
– API exposes where client register a call back but no
mechanism to de-register them.
Solution
● Nullify obsolete references
● Don't make it a norm and use judiciously. Best
way to let variable fall out of scope
● Cache – WeakHashMap Enteries will be
removes automatically after they become
obsolete
● Store only weak references to callbacks
Avoid finalizers
● Unpredictable, dangerous and unnecessary
● Implementation of finalizers is JVM implementation dependent
● When finalizer will be invoked is a function of the VM's
garbage collection algorithm
● System.gc does not guarantee finalizers execute
● Performance penalty with finalizers
● Don't rely on finalizer to ensure program correctness. Your
design is flawed
● Instead
– Make use of explicit termination methods. try catch finally.
Thank you

More Related Content

Similar to Effective java - Creating and Destroying Objects

Similar to Effective java - Creating and Destroying Objects (20)

Effective java
Effective javaEffective java
Effective java
 
Prototype design patterns
Prototype design patternsPrototype design patterns
Prototype design patterns
 
Javascript Common Design Patterns
Javascript Common Design PatternsJavascript Common Design Patterns
Javascript Common Design Patterns
 
Creating and destroying objects
Creating and destroying objectsCreating and destroying objects
Creating and destroying objects
 
Object Oriented Prograring(OOP) java
Object Oriented Prograring(OOP) javaObject Oriented Prograring(OOP) java
Object Oriented Prograring(OOP) java
 
Prototype_pattern
Prototype_patternPrototype_pattern
Prototype_pattern
 
Design patterns in javascript
Design patterns in javascriptDesign patterns in javascript
Design patterns in javascript
 
Object oriented programming in java
Object oriented programming in javaObject oriented programming in java
Object oriented programming in java
 
When and how to explore: an engineer's guide
When and how to explore:  an engineer's guideWhen and how to explore:  an engineer's guide
When and how to explore: an engineer's guide
 
Singleton Pattern (Sole Object with Global Access)
Singleton Pattern (Sole Object with Global Access)Singleton Pattern (Sole Object with Global Access)
Singleton Pattern (Sole Object with Global Access)
 
Design_Patterns_Dr.CM.ppt
Design_Patterns_Dr.CM.pptDesign_Patterns_Dr.CM.ppt
Design_Patterns_Dr.CM.ppt
 
TDD done right - tests immutable to refactor
TDD done right - tests immutable to refactorTDD done right - tests immutable to refactor
TDD done right - tests immutable to refactor
 
effective java
effective javaeffective java
effective java
 
Creational Design Patterns.pptx
Creational Design Patterns.pptxCreational Design Patterns.pptx
Creational Design Patterns.pptx
 
Factory Design Pattern
Factory Design PatternFactory Design Pattern
Factory Design Pattern
 
Exploring Kotlin language basics for Android App development
Exploring Kotlin language basics for Android App developmentExploring Kotlin language basics for Android App development
Exploring Kotlin language basics for Android App development
 
8. objects & classes
8. objects & classes8. objects & classes
8. objects & classes
 
Concurrency in Java
Concurrency in JavaConcurrency in Java
Concurrency in Java
 
Concurrent Programming in Java
Concurrent Programming in JavaConcurrent Programming in Java
Concurrent Programming in Java
 
Unit testing in xcode 8 with swift
Unit testing in xcode 8 with swiftUnit testing in xcode 8 with swift
Unit testing in xcode 8 with swift
 

Recently uploaded

Recently uploaded (20)

Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
 
Agnieszka Andrzejewska - BIM School Course in Kraków
Agnieszka Andrzejewska - BIM School Course in KrakówAgnieszka Andrzejewska - BIM School Course in Kraków
Agnieszka Andrzejewska - BIM School Course in Kraków
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
 
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
 
GraphAware - Transforming policing with graph-based intelligence analysis
GraphAware - Transforming policing with graph-based intelligence analysisGraphAware - Transforming policing with graph-based intelligence analysis
GraphAware - Transforming policing with graph-based intelligence analysis
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
 
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
 
AI/ML Infra Meetup | Reducing Prefill for LLM Serving in RAG
AI/ML Infra Meetup | Reducing Prefill for LLM Serving in RAGAI/ML Infra Meetup | Reducing Prefill for LLM Serving in RAG
AI/ML Infra Meetup | Reducing Prefill for LLM Serving in RAG
 
Designing for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web ServicesDesigning for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web Services
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
 

Effective java - Creating and Destroying Objects

  • 1. Creating & Destroying Objects Reference: Effective Java - Joshua Bloch -Rohit Vaidya
  • 2. Agenda ● Discuss over object creation and destruction ● Study best practices ● Use profiler to go over how good or bad code is
  • 3. Items ● Item1 Consider Static factory methods ● Item2 Consider builders ● Item3 Enforce Singleton,private constructors or enum type ● Item4 Enforce non-instanstiability private constructors ● Item5 Avoid creating unnecessary Objects ● Item6 Avoid finalizers
  • 4. Creating Objects ● When and how to create Objects ● How to avoid creating them ● Ensure they are destroyed ● Cleanup before destruction
  • 5. Item 1 Consider static factory methods instead of constructors
  • 6. Item 1 Premise ● Create an object ● Implicitly not create objects when unnecessary ● Ability to create a object of subtype
  • 7. Item1 - Solution ● Provide static factory methods ● Advantages – Unlike constructors they have names – Not required each time you create a new object ● E.g: Boolean.valueof(boolean) – never creates a object – Can return a object of any subtype of return type ● Disadvantages – Classes without public or protected members cannot be sub classed ● This has a hidden advantage – Not easily distinguishable from other static factory methods
  • 8. Item 2 Consider builder when faced with many constructor parameter
  • 9. Item 2 Premise ● Many parameter constructors or static factories do not scale – Hell for the client ● Telescoping constructor pattern – Why its bad? Hard to read/write code ● Java Beans pattern – Inconsistent path way through its construction – Does not allow your class to be immutable. Setters!!!
  • 10. Item 2 Solution ● Builders!!! – Makes your class immutable. Important – Makes it easy to read and write code – Builders allows you to set invariants. If Invariant is not satisfied throw IllegalArgumentException – Builders can have multiple varargs where as constructor only one ● “The Builder pattern is a good choice when designing classes whose constructors or static factories would have more than a handful of parameters"
  • 11. Item 3 Enforce the singleton property with a private constructor or an enum Type
  • 12. Item 3 - Premise ● Make a class singleton ● Avoid reflection attacks on singleton classes made singleton conventionally – AccessibleObject.setAccessible ● Serialization making multiple copies of the same object
  • 13. Item3-Solution ● Have a public static final field which contains the instance – Class declaration makes it evident, its singleton ● Have a private static field with the factory method returning the instance – The factory API can be easily modified to make it non singleton ● Use enum to create singletons ● Have the constructor throw an exception – to solve Reflection problem ● Make all the field transient and implement a resolveObject API to resolve serialization problem
  • 14. Item 4 Enforce non-instantiability with a private constructor
  • 15. Item 4 – Premise ● Want to write a class which is a group of static methods ● Write group of methods on primitive values or arrays. e.g: java.util.Arrays java.lang.Math ● Don't create an object where its non-sensical to do so – Utility Classes
  • 16. Item 4 - Solution ● Simple: Add a private constructor. ● If you don't? - A default constructor gets generated. You can still do a X obj = new X(); //This is bad. ● You have instantiated a class when not required ● Positive Side Effect: Can't be subclasses
  • 17. Item 5 Avoid creating unnecessary Objects
  • 18. Premise ● Reuse objects ● Consequently avoid creating new instances ● Reuse immutable objects and mutable objects ● Avoid accidentally creating objects
  • 19. Solution ● String pool of-course!!! – String s = new String(“string”);//Code smell ● Use static factory methods for object creation – Boolean(String) //Code smell ● Reuse Mutable Objects. Assuming these objects are not expected to be mutated ● Safe to reuse immutable objects ● Beware of auto-boxing
  • 20. Item 5 - Snippets
  • 23. Item 5 – Fix it
  • 25. Item 5 – After fix
  • 27. Premise ● Need to understand Memory Leaks first ● Don't misunderstand Java Garbage collector cleans it all – Obsolete References to blame. – References that will never be referenced again ● Memory Leaks in caches ● Listeners and their callbacks, another culprit – API exposes where client register a call back but no mechanism to de-register them.
  • 28. Solution ● Nullify obsolete references ● Don't make it a norm and use judiciously. Best way to let variable fall out of scope ● Cache – WeakHashMap Enteries will be removes automatically after they become obsolete ● Store only weak references to callbacks
  • 29. Avoid finalizers ● Unpredictable, dangerous and unnecessary ● Implementation of finalizers is JVM implementation dependent ● When finalizer will be invoked is a function of the VM's garbage collection algorithm ● System.gc does not guarantee finalizers execute ● Performance penalty with finalizers ● Don't rely on finalizer to ensure program correctness. Your design is flawed ● Instead – Make use of explicit termination methods. try catch finally.