SlideShare une entreprise Scribd logo
1  sur  38
ITEM 1 Consider static factory methods instead of constructors
Is simply a static method that returns an instance of the class 				ADVANTAGES They have names.  They are not required to create a new object each time they are invoked. They can return an object of any subtype of their return type. Best example for this is : Collection API They reduce verbosity of creating parameterized type instances. 				DISADVANTAGES When providing only static factory methods, classes without public or protected constructors cannot be subclassed. They are not readily distinguishable from other static methods static factory methods
Example Car Factory produces different Car objects Ordinary Different classes implement Car interface Directly instantiate car objects Need to modify client to change cars Using pattern Use carFactory class to produce car objects Can change cars by changing carFactory Factory Pattern
class 350Z implements Car;		// fast car class Ram implements Car;		// truck class Accord implements Car;	           // family car Car fast = new 350Z();			// returns fast car public class carFactory {    public static Car create(String type) {      if (type.equals("fast"))		return new 350Z();      if (type.equals("truck"))		return new Ram();      else if (type.equals(“family”)	return new Accord();    } } Car fast = carFactory.create("fast"); // returns fast car Factory Example
By default, constructors should be preferred, because they are simpler to understand and write.  However, if you specifically need to decouple the construction niceties of an object from its semantic meaning as understood by the client code, you'd be better off using factories. Constructors
Use static factory methods for a more intuitive API, to improve performance via object-caching, to implement singletons, in interface-based frameworks, and to return objects of private classes.  Use constructors in classes designed for inheritance (there shouldn’t be many of these) and for greater visibility in API documentation (since they appear in a separate table in standard Javadocs). The verdict?
Item 2 Consider a builder when faced with many constructor parameters
Telescoping Constructor Pattern JavaBeans Pattern Builder Pattern
This method is the traditional way of dealing with the problem of many constructor parameters.  The problem being that but it is hard to write client code when there are many parameters, and harder still to read it. Telescoping Constructor Pattern
The approach is that we call the parameterless constructor to create the object and then call setter methods to set each required parameter and each optional parameter of interest. Limitations Because construction is split across multiple calls a JavaBean may be in an inconsistent state partway through its construction. This pattern precludes the possibility of making a class immutable JavaBeans Pattern
The third alternative that combines the safety of the telescoping constructor pattern with the readability of the JavaBeans pattern is the builder pattern. Instead of making the desired object directly, the client calls a constructor (or static factory) with all of the required parameters and gets a builder object. Then the client calls setter-like methods on the builder object to set each optional parameter of interest. Builder Battern
	public Builder calories(intval) { 	calories = val; return this;  	} 	public Builder fat(intval) {  		fat = val; return this;  	} 	public Builder carbohydrate(intval) {  		carbohydrate = val;  		return this;  	} 	public Builder sodium(intval) { sodium = val; return this;  	} 	public NutritionFacts build() { 		return new NutritionFacts(this); 	} } private NutritionFacts(Builder builder) { servingSize = builder.servingSize; 	servings = builder.servings; 	calories = builder.calories; 	fat = builder.fat; 	sodium = builder.sodium; 	carbohydrate = builder.carbohydrate; } }  NutritionFactscocaCola = new NutritionFacts.Builder(240, 8). calories(100).sodium(35).carbohydrate(27).build(); // Builder Pattern public class NutritionFacts { 	private final intservingSize; 	private final int servings; 	private final int calories; 	private final int fat; 	private final int sodium; 	private final int carbohydrate; 	public static class Builder { 	// Required parameters 		private final intservingSize; 		private final int servings; 	// Optional parameters-initialized to //default values 		private int calories = 0; 		private int fat = 0; 		private int carbohydrate = 0; 		private int sodium = 0; 	public Builder(intservingSize, int servings) { this.servingSize = servingSize; this.servings = servings; 	}
Advantages It is flexible in the sense that a single builder can be used to build multiple objects.  The parameters of the builder can be tweaked between object creations to vary the objects. Disadvantages In order to create an object, you must first create its builder which could be a problem in some performance critical situations.  Also, the Builder pattern is more verbose than the telescoping constructor pattern, so it should be used only if there are enough parameters, say four or more
The Builder pattern is a good choice when designing classes whose constructors or static factories would have more than a handful of parameters, especially if most of those parameters are optional.  Client code is much easier to read and write with builders than with the traditional telescoping constructor pattern. Builders are much safer than JavaBeans. To Summarize
Item 3 Enforce the singleton property with a private constructor or an enum type
A singleton is simply a class that is instantiated exactly once Often in designing a system, we want to control how an object is used, and prevent others (ourselves included) from making copies of it or creating new instances.  Scenario/Use-Case Consider a central configuration object that stores setup information. It should have one and one only instance - a global copy accessible from any part of the application, including any threads that are running. Creating a new configuration object and using it would be fairly useless, as other parts of the application might be looking at the old configuration object, and changes to application settings wouldn't always be acted upon. So this is one of the cases wherein we would need the concept of singleton. singleton
Prior to 1.5 public class SingletonObject {  		private static SingletonObject ref;  privateSingletonObject() {  			// no code required  		}	  	public static SingletonObjectgetSingletonObject() {  		if (ref == null)  		ref = new SingletonObject();  		return ref;  	}  } Approaches for singleton
Preventing thread problems with your singleton public static synchronized SingletonObjectgetSingletonObject() This is important because this would prevent two threads from calling the getSingletonObject() method at the same time. If one thread entered the method just after the other, you could end up calling the SingletonObject constructor twice and returning different values. Another possible way to violate the design principles of the singleton is with the help of the clone() method which would create and return a copy of the singleton object.  So, to avoid this, we must add a clone() method of our own, and throw a CloneNotSupportedException.
How does serialization affects singleton?? it is not sufficient merely to add implements Serializable to its declaration. To maintain the singleton guarantee, you have to declare all instance fields transient and provide a readResolve() method. Otherwise, each time a serialized instance is deserialized, a new instance will be created.
For example: // readResolve for instance control - private Object readResolve() { 		// Return the one true Elvis and let the garbage collector take 	//care of the Elvis impersonator. return ref; 	} This method ignores the deserialized object, returning the distinguished instance that was created when the class was initialized
As of release 1.5 // Enum singleton - the preferred approach public enum Elvis { 		INSTANCE; 		public void leaveTheBuilding() { ... } 	} This approach is functionally equivalent to the public field approach, except that it is more concise, provides the serialization machinery for free, and provides an ironclad guarantee against multiple instantiation, even in the face of sophisticated serialization or reflection attacks. While this approach has yet to be widely adopted, a single-element enum type is the best way to implement a singleton.
Item 4 Enforce non-instantiability with a private constructor
Use case/ scenario Creating a utility class which is just a collection of static maethods Such utility classes are not designed to be instantiated because the class is just a grouping of static methods and static fields so an instance would be nonsensical.
public class UtilityClass{ //Suppress default constructor for noninstantiability private UtilityClass() { 	throw new AssertionError(); 	} 	} The AssertionError provides insurance in case the constructor is accidentally invoked from within the class. Noninstantiable utility class
Item 5 Avoid creating unnecessary objects
It is often appropriate to reuse a single object instead of creating a new functionally equivalent object each time it is needed.  Reuse enhances performane as it is faster. String s = new String(“nishant");//never do! String s = “nishant"; This was the case of immutable objects but even for mutable objects you should reuse them if you know they won’t be modified. ,[object Object],[object Object]
Item 6 Eliminate obsolete object references
An obsolete reference is simply a reference that will never be dereferenced again. This can be explained with the help of the following example…. Stack example What is an obsolete reference ?
Whenever a class manages its own memory, the programmer should be alert for memory leaks. Simply put, it manages its own memory. The elements in the active portion of the array are allocated, and those in the remainder of the array are free.  The garbage collector has no way of knowing this For the GC all of the object references in the elements array are equally valid.  Only the programmer knows that the inactive portion of the array is unimportant.  The programmer effectively communicates this fact to the garbage collector by manually nulling out array elements as soon as they become part of the inactive portion. So where is the problem ?
Whenever an element is freed, any object references contained in the element should be nulled out. Another common source of memory leaks is caches When should you null out a reference ?
Item 7 Avoid finalizers
In C++, destructors are the normal way to reclaim the resources associated with an object, a necessary counterpart to constructors.  In Java, the garbage collector reclaims the storage associated with an object when it becomes unreachable, requiring no special effort on the part of the programmer.  C++ destructors are also used to reclaim other nonmemory resources.  In Java, the try finally block is generally used for this purpose.
There is no guarantee they’ll be executed promptly so never do anything time-critical in a finalizer. The promptness with which finalizers are executed is primarily a function of the garbage collection algorithm, which varies widely from JVM to JVM It is entirely possible, even likely, that a program terminates without executing finalizers on some objects that are no longer reachable. As a consequence, you should never depend on a finalizer to update critical persistent state Limitations
If an uncaught exception is thrown during finalization, the exception is ignored, and finalization of that object terminates. Uncaught exceptions can leave objects in a corrupt state. If another thread attempts to use such a corrupted object, arbitrary nondeterministic behavior may result. Normally, an uncaught exception will terminate the thread and print a stack trace, but not if it occurs in a finalizer. There is a severe performance penalty for using finalizers. On my machine, the time to create and destroy a simple object is about 5.6 ns. Adding a finalizer increases the time to 2,400 ns Contd.
Explicit termination methods are typically used in combination with the try-finally construct to ensure termination Examples:	close method, cancel  method  // try-finally block guarantees execution of termination method Foofoo = new Foo(...); 		try { 			// Do what must be done with foo 			... 		}	  		finally { foo.terminate(); // Explicit termination 					//method 		} Work-around
They have 2 legitimate uses: One is to act as a “safety net” in case the owner of an object forgets to call its explicit termination method A second legitimate use of finalizers concerns objects with native peers. A native peer is a native object to which a normal object delegates via native methods. Because a native peer is not a normal object, the garbage collector doesn’t know about it and can’t reclaim it when its Java peer is reclaimed. A finalizer is an appropriate vehicle for performing this task, assuming the native peer holds nocritical resources So what are the finalizers good for ?
AWT uses native code (code specific to a single operating system) to display its components. Each implementation of the Jave Runtime Environment (JRE) must provide native implementations of Buttons, Labels, Panels, and all of the other AWT components. Whenever you use an AWT component, if forwards all of its drawing requests to a piece of native code. This allows you to generically use an AWT Button in your application, but the Button appears as a Windows Button, a Motif Button, a Mac Button, or a real button on whatever platform you are running. These pieces of native code are referred to as peers, as they share the responsibility for displaying a component. Peer code includes native code to display components, as well as draw lines, determine platform specifics such as current screen size, and other native platform issues.
Creating and destroying objects

Contenu connexe

Tendances

ConsTRUCTION AND DESTRUCTION
ConsTRUCTION AND DESTRUCTIONConsTRUCTION AND DESTRUCTION
ConsTRUCTION AND DESTRUCTIONShweta Shah
 
OCA Java SE 8 Exam Chapter 4 Methods Encapsulation
OCA Java SE 8 Exam Chapter 4 Methods EncapsulationOCA Java SE 8 Exam Chapter 4 Methods Encapsulation
OCA Java SE 8 Exam Chapter 4 Methods Encapsulationİbrahim Kürce
 
Strategy and Template Pattern
Strategy and Template PatternStrategy and Template Pattern
Strategy and Template PatternJonathan Simon
 
Type Annotations in Java 8
Type Annotations in Java 8 Type Annotations in Java 8
Type Annotations in Java 8 FinLingua, Inc.
 
The Little Wonders of C# 6
The Little Wonders of C# 6The Little Wonders of C# 6
The Little Wonders of C# 6BlackRabbitCoder
 
Constructor destructor.ppt
Constructor destructor.pptConstructor destructor.ppt
Constructor destructor.pptKarthik Sekar
 
More Little Wonders of C#/.NET
More Little Wonders of C#/.NETMore Little Wonders of C#/.NET
More Little Wonders of C#/.NETBlackRabbitCoder
 
Singleton design pattern
Singleton design patternSingleton design pattern
Singleton design pattern11prasoon
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorialsakreyi
 
Scope demystified - AngularJS
Scope demystified - AngularJSScope demystified - AngularJS
Scope demystified - AngularJSSumanth krishna
 
Iterator - a powerful but underappreciated design pattern
Iterator - a powerful but underappreciated design patternIterator - a powerful but underappreciated design pattern
Iterator - a powerful but underappreciated design patternNitin Bhide
 
Java Core Parctical
Java Core ParcticalJava Core Parctical
Java Core ParcticalGaurav Mehta
 
Net framework session01
Net framework session01Net framework session01
Net framework session01Vivek chan
 
Design Patterns Illustrated
Design Patterns IllustratedDesign Patterns Illustrated
Design Patterns IllustratedHerman Peeren
 
Advanced java interview questions
Advanced java interview questionsAdvanced java interview questions
Advanced java interview questionsrithustutorials
 

Tendances (20)

ConsTRUCTION AND DESTRUCTION
ConsTRUCTION AND DESTRUCTIONConsTRUCTION AND DESTRUCTION
ConsTRUCTION AND DESTRUCTION
 
OCA Java SE 8 Exam Chapter 4 Methods Encapsulation
OCA Java SE 8 Exam Chapter 4 Methods EncapsulationOCA Java SE 8 Exam Chapter 4 Methods Encapsulation
OCA Java SE 8 Exam Chapter 4 Methods Encapsulation
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
Strategy and Template Pattern
Strategy and Template PatternStrategy and Template Pattern
Strategy and Template Pattern
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
Type Annotations in Java 8
Type Annotations in Java 8 Type Annotations in Java 8
Type Annotations in Java 8
 
The Little Wonders of C# 6
The Little Wonders of C# 6The Little Wonders of C# 6
The Little Wonders of C# 6
 
Constructor destructor.ppt
Constructor destructor.pptConstructor destructor.ppt
Constructor destructor.ppt
 
Of Lambdas and LINQ
Of Lambdas and LINQOf Lambdas and LINQ
Of Lambdas and LINQ
 
Introduction to JAVA
Introduction to JAVAIntroduction to JAVA
Introduction to JAVA
 
More Little Wonders of C#/.NET
More Little Wonders of C#/.NETMore Little Wonders of C#/.NET
More Little Wonders of C#/.NET
 
Singleton design pattern
Singleton design patternSingleton design pattern
Singleton design pattern
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorials
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Scope demystified - AngularJS
Scope demystified - AngularJSScope demystified - AngularJS
Scope demystified - AngularJS
 
Iterator - a powerful but underappreciated design pattern
Iterator - a powerful but underappreciated design patternIterator - a powerful but underappreciated design pattern
Iterator - a powerful but underappreciated design pattern
 
Java Core Parctical
Java Core ParcticalJava Core Parctical
Java Core Parctical
 
Net framework session01
Net framework session01Net framework session01
Net framework session01
 
Design Patterns Illustrated
Design Patterns IllustratedDesign Patterns Illustrated
Design Patterns Illustrated
 
Advanced java interview questions
Advanced java interview questionsAdvanced java interview questions
Advanced java interview questions
 

Similaire à Creating and destroying objects

Design patterns in Java - Monitis 2017
Design patterns in Java - Monitis 2017Design patterns in Java - Monitis 2017
Design patterns in Java - Monitis 2017Arsen Gasparyan
 
Layers of Smalltalk Application
Layers of Smalltalk ApplicationLayers of Smalltalk Application
Layers of Smalltalk Applicationspeludner
 
Javascript Common Design Patterns
Javascript Common Design PatternsJavascript Common Design Patterns
Javascript Common Design PatternsPham Huy Tung
 
P Training Presentation
P Training PresentationP Training Presentation
P Training PresentationGaurav Tyagi
 
Introduction to design_patterns
Introduction to design_patternsIntroduction to design_patterns
Introduction to design_patternsamitarcade
 
Effective Java. By materials of Josch Bloch's book
Effective Java. By materials of Josch Bloch's bookEffective Java. By materials of Josch Bloch's book
Effective Java. By materials of Josch Bloch's bookRoman Tsypuk
 
Prototype design patterns
Prototype design patternsPrototype design patterns
Prototype design patternsThaichor Seng
 
The Singleton Pattern Presentation
The Singleton Pattern PresentationThe Singleton Pattern Presentation
The Singleton Pattern PresentationJAINIK PATEL
 
Design patterns in java script, jquery, angularjs
Design patterns in java script, jquery, angularjsDesign patterns in java script, jquery, angularjs
Design patterns in java script, jquery, angularjsRavi Bhadauria
 
Javascript Object Patterns.pptx
Javascript Object Patterns.pptxJavascript Object Patterns.pptx
Javascript Object Patterns.pptxAlaref Abushaala
 
Creational pattern 2
Creational pattern 2Creational pattern 2
Creational pattern 2Naga Muruga
 
Salesforce lwc development workshops session #6
Salesforce lwc development workshops  session #6Salesforce lwc development workshops  session #6
Salesforce lwc development workshops session #6Rahul Gawale
 
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)Sameer Rathoud
 

Similaire à Creating and destroying objects (20)

Design patterns in Java - Monitis 2017
Design patterns in Java - Monitis 2017Design patterns in Java - Monitis 2017
Design patterns in Java - Monitis 2017
 
Layers of Smalltalk Application
Layers of Smalltalk ApplicationLayers of Smalltalk Application
Layers of Smalltalk Application
 
Software Design Patterns
Software Design PatternsSoftware Design Patterns
Software Design Patterns
 
Javascript Common Design Patterns
Javascript Common Design PatternsJavascript Common Design Patterns
Javascript Common Design Patterns
 
P Training Presentation
P Training PresentationP Training Presentation
P Training Presentation
 
Introduction to design_patterns
Introduction to design_patternsIntroduction to design_patterns
Introduction to design_patterns
 
Designing Better API
Designing Better APIDesigning Better API
Designing Better API
 
Effective Java. By materials of Josch Bloch's book
Effective Java. By materials of Josch Bloch's bookEffective Java. By materials of Josch Bloch's book
Effective Java. By materials of Josch Bloch's book
 
Prototype design patterns
Prototype design patternsPrototype design patterns
Prototype design patterns
 
Prototype pattern
Prototype patternPrototype pattern
Prototype pattern
 
The Singleton Pattern Presentation
The Singleton Pattern PresentationThe Singleton Pattern Presentation
The Singleton Pattern Presentation
 
Sda 8
Sda   8Sda   8
Sda 8
 
Design patterns in java script, jquery, angularjs
Design patterns in java script, jquery, angularjsDesign patterns in java script, jquery, angularjs
Design patterns in java script, jquery, angularjs
 
Javascript Object Patterns.pptx
Javascript Object Patterns.pptxJavascript Object Patterns.pptx
Javascript Object Patterns.pptx
 
Creational pattern 2
Creational pattern 2Creational pattern 2
Creational pattern 2
 
Backbonejs
BackbonejsBackbonejs
Backbonejs
 
Salesforce lwc development workshops session #6
Salesforce lwc development workshops  session #6Salesforce lwc development workshops  session #6
Salesforce lwc development workshops session #6
 
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)
 
C# features
C# featuresC# features
C# features
 
Factory Method Pattern
Factory Method PatternFactory Method Pattern
Factory Method Pattern
 

Plus de Sandeep Chawla

Plus de Sandeep Chawla (6)

Exception
ExceptionException
Exception
 
Classes & Interfaces
Classes & InterfacesClasses & Interfaces
Classes & Interfaces
 
Methods common to all objects
Methods common to all objectsMethods common to all objects
Methods common to all objects
 
Concurrency
ConcurrencyConcurrency
Concurrency
 
Maven Introduction
Maven IntroductionMaven Introduction
Maven Introduction
 
Sandeep Chawla Visual Resume
Sandeep Chawla Visual ResumeSandeep Chawla Visual Resume
Sandeep Chawla Visual Resume
 

Dernier

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
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
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
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsRavi Sanghani
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
QCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesQCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesBernd Ruecker
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Hiroshi SHIBATA
 
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesMuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesManik S Magar
 
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
 
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
 
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
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Farhan Tariq
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
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
 
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
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI AgeCprime
 
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxGenerative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxfnnc6jmgwh
 
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
 
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
 

Dernier (20)

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
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
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
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and Insights
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
QCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesQCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architectures
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024
 
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesMuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
 
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
 
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
 
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
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
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
 
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
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI Age
 
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxGenerative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
 
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
 
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
 

Creating and destroying objects

  • 1. ITEM 1 Consider static factory methods instead of constructors
  • 2. Is simply a static method that returns an instance of the class ADVANTAGES They have names. They are not required to create a new object each time they are invoked. They can return an object of any subtype of their return type. Best example for this is : Collection API They reduce verbosity of creating parameterized type instances. DISADVANTAGES When providing only static factory methods, classes without public or protected constructors cannot be subclassed. They are not readily distinguishable from other static methods static factory methods
  • 3. Example Car Factory produces different Car objects Ordinary Different classes implement Car interface Directly instantiate car objects Need to modify client to change cars Using pattern Use carFactory class to produce car objects Can change cars by changing carFactory Factory Pattern
  • 4. class 350Z implements Car; // fast car class Ram implements Car; // truck class Accord implements Car; // family car Car fast = new 350Z(); // returns fast car public class carFactory { public static Car create(String type) { if (type.equals("fast")) return new 350Z(); if (type.equals("truck")) return new Ram(); else if (type.equals(“family”) return new Accord(); } } Car fast = carFactory.create("fast"); // returns fast car Factory Example
  • 5. By default, constructors should be preferred, because they are simpler to understand and write. However, if you specifically need to decouple the construction niceties of an object from its semantic meaning as understood by the client code, you'd be better off using factories. Constructors
  • 6. Use static factory methods for a more intuitive API, to improve performance via object-caching, to implement singletons, in interface-based frameworks, and to return objects of private classes. Use constructors in classes designed for inheritance (there shouldn’t be many of these) and for greater visibility in API documentation (since they appear in a separate table in standard Javadocs). The verdict?
  • 7. Item 2 Consider a builder when faced with many constructor parameters
  • 8. Telescoping Constructor Pattern JavaBeans Pattern Builder Pattern
  • 9. This method is the traditional way of dealing with the problem of many constructor parameters. The problem being that but it is hard to write client code when there are many parameters, and harder still to read it. Telescoping Constructor Pattern
  • 10. The approach is that we call the parameterless constructor to create the object and then call setter methods to set each required parameter and each optional parameter of interest. Limitations Because construction is split across multiple calls a JavaBean may be in an inconsistent state partway through its construction. This pattern precludes the possibility of making a class immutable JavaBeans Pattern
  • 11. The third alternative that combines the safety of the telescoping constructor pattern with the readability of the JavaBeans pattern is the builder pattern. Instead of making the desired object directly, the client calls a constructor (or static factory) with all of the required parameters and gets a builder object. Then the client calls setter-like methods on the builder object to set each optional parameter of interest. Builder Battern
  • 12. public Builder calories(intval) { calories = val; return this; } public Builder fat(intval) { fat = val; return this; } public Builder carbohydrate(intval) { carbohydrate = val; return this; } public Builder sodium(intval) { sodium = val; return this; } public NutritionFacts build() { return new NutritionFacts(this); } } private NutritionFacts(Builder builder) { servingSize = builder.servingSize; servings = builder.servings; calories = builder.calories; fat = builder.fat; sodium = builder.sodium; carbohydrate = builder.carbohydrate; } } NutritionFactscocaCola = new NutritionFacts.Builder(240, 8). calories(100).sodium(35).carbohydrate(27).build(); // Builder Pattern public class NutritionFacts { private final intservingSize; private final int servings; private final int calories; private final int fat; private final int sodium; private final int carbohydrate; public static class Builder { // Required parameters private final intservingSize; private final int servings; // Optional parameters-initialized to //default values private int calories = 0; private int fat = 0; private int carbohydrate = 0; private int sodium = 0; public Builder(intservingSize, int servings) { this.servingSize = servingSize; this.servings = servings; }
  • 13. Advantages It is flexible in the sense that a single builder can be used to build multiple objects. The parameters of the builder can be tweaked between object creations to vary the objects. Disadvantages In order to create an object, you must first create its builder which could be a problem in some performance critical situations. Also, the Builder pattern is more verbose than the telescoping constructor pattern, so it should be used only if there are enough parameters, say four or more
  • 14. The Builder pattern is a good choice when designing classes whose constructors or static factories would have more than a handful of parameters, especially if most of those parameters are optional. Client code is much easier to read and write with builders than with the traditional telescoping constructor pattern. Builders are much safer than JavaBeans. To Summarize
  • 15. Item 3 Enforce the singleton property with a private constructor or an enum type
  • 16. A singleton is simply a class that is instantiated exactly once Often in designing a system, we want to control how an object is used, and prevent others (ourselves included) from making copies of it or creating new instances. Scenario/Use-Case Consider a central configuration object that stores setup information. It should have one and one only instance - a global copy accessible from any part of the application, including any threads that are running. Creating a new configuration object and using it would be fairly useless, as other parts of the application might be looking at the old configuration object, and changes to application settings wouldn't always be acted upon. So this is one of the cases wherein we would need the concept of singleton. singleton
  • 17. Prior to 1.5 public class SingletonObject { private static SingletonObject ref; privateSingletonObject() { // no code required } public static SingletonObjectgetSingletonObject() { if (ref == null) ref = new SingletonObject(); return ref; } } Approaches for singleton
  • 18. Preventing thread problems with your singleton public static synchronized SingletonObjectgetSingletonObject() This is important because this would prevent two threads from calling the getSingletonObject() method at the same time. If one thread entered the method just after the other, you could end up calling the SingletonObject constructor twice and returning different values. Another possible way to violate the design principles of the singleton is with the help of the clone() method which would create and return a copy of the singleton object.  So, to avoid this, we must add a clone() method of our own, and throw a CloneNotSupportedException.
  • 19. How does serialization affects singleton?? it is not sufficient merely to add implements Serializable to its declaration. To maintain the singleton guarantee, you have to declare all instance fields transient and provide a readResolve() method. Otherwise, each time a serialized instance is deserialized, a new instance will be created.
  • 20. For example: // readResolve for instance control - private Object readResolve() { // Return the one true Elvis and let the garbage collector take //care of the Elvis impersonator. return ref; } This method ignores the deserialized object, returning the distinguished instance that was created when the class was initialized
  • 21. As of release 1.5 // Enum singleton - the preferred approach public enum Elvis { INSTANCE; public void leaveTheBuilding() { ... } } This approach is functionally equivalent to the public field approach, except that it is more concise, provides the serialization machinery for free, and provides an ironclad guarantee against multiple instantiation, even in the face of sophisticated serialization or reflection attacks. While this approach has yet to be widely adopted, a single-element enum type is the best way to implement a singleton.
  • 22. Item 4 Enforce non-instantiability with a private constructor
  • 23. Use case/ scenario Creating a utility class which is just a collection of static maethods Such utility classes are not designed to be instantiated because the class is just a grouping of static methods and static fields so an instance would be nonsensical.
  • 24. public class UtilityClass{ //Suppress default constructor for noninstantiability private UtilityClass() { throw new AssertionError(); } } The AssertionError provides insurance in case the constructor is accidentally invoked from within the class. Noninstantiable utility class
  • 25. Item 5 Avoid creating unnecessary objects
  • 26.
  • 27. Item 6 Eliminate obsolete object references
  • 28. An obsolete reference is simply a reference that will never be dereferenced again. This can be explained with the help of the following example…. Stack example What is an obsolete reference ?
  • 29. Whenever a class manages its own memory, the programmer should be alert for memory leaks. Simply put, it manages its own memory. The elements in the active portion of the array are allocated, and those in the remainder of the array are free. The garbage collector has no way of knowing this For the GC all of the object references in the elements array are equally valid. Only the programmer knows that the inactive portion of the array is unimportant. The programmer effectively communicates this fact to the garbage collector by manually nulling out array elements as soon as they become part of the inactive portion. So where is the problem ?
  • 30. Whenever an element is freed, any object references contained in the element should be nulled out. Another common source of memory leaks is caches When should you null out a reference ?
  • 31. Item 7 Avoid finalizers
  • 32. In C++, destructors are the normal way to reclaim the resources associated with an object, a necessary counterpart to constructors. In Java, the garbage collector reclaims the storage associated with an object when it becomes unreachable, requiring no special effort on the part of the programmer. C++ destructors are also used to reclaim other nonmemory resources. In Java, the try finally block is generally used for this purpose.
  • 33. There is no guarantee they’ll be executed promptly so never do anything time-critical in a finalizer. The promptness with which finalizers are executed is primarily a function of the garbage collection algorithm, which varies widely from JVM to JVM It is entirely possible, even likely, that a program terminates without executing finalizers on some objects that are no longer reachable. As a consequence, you should never depend on a finalizer to update critical persistent state Limitations
  • 34. If an uncaught exception is thrown during finalization, the exception is ignored, and finalization of that object terminates. Uncaught exceptions can leave objects in a corrupt state. If another thread attempts to use such a corrupted object, arbitrary nondeterministic behavior may result. Normally, an uncaught exception will terminate the thread and print a stack trace, but not if it occurs in a finalizer. There is a severe performance penalty for using finalizers. On my machine, the time to create and destroy a simple object is about 5.6 ns. Adding a finalizer increases the time to 2,400 ns Contd.
  • 35. Explicit termination methods are typically used in combination with the try-finally construct to ensure termination Examples: close method, cancel method // try-finally block guarantees execution of termination method Foofoo = new Foo(...); try { // Do what must be done with foo ... } finally { foo.terminate(); // Explicit termination //method } Work-around
  • 36. They have 2 legitimate uses: One is to act as a “safety net” in case the owner of an object forgets to call its explicit termination method A second legitimate use of finalizers concerns objects with native peers. A native peer is a native object to which a normal object delegates via native methods. Because a native peer is not a normal object, the garbage collector doesn’t know about it and can’t reclaim it when its Java peer is reclaimed. A finalizer is an appropriate vehicle for performing this task, assuming the native peer holds nocritical resources So what are the finalizers good for ?
  • 37. AWT uses native code (code specific to a single operating system) to display its components. Each implementation of the Jave Runtime Environment (JRE) must provide native implementations of Buttons, Labels, Panels, and all of the other AWT components. Whenever you use an AWT component, if forwards all of its drawing requests to a piece of native code. This allows you to generically use an AWT Button in your application, but the Button appears as a Windows Button, a Motif Button, a Mac Button, or a real button on whatever platform you are running. These pieces of native code are referred to as peers, as they share the responsibility for displaying a component. Peer code includes native code to display components, as well as draw lines, determine platform specifics such as current screen size, and other native platform issues.