SlideShare a Scribd company logo
JAVA
CONSIDER STATIC FACTORY METHODS INSTEAD OF CONSTRUCTORS
Ye Win
11/21/2015
Contents
• Preface (Summary)
• Static Factory Methods
• Advantages
• Disadvantages
• Summary (Preface)
Preface (Summary)
In preface, static factory methods and public constructors both have
their uses, and it pays to understand their relative merits. Often static
factories are preferable, so avoid the reflex to provide public
constructors without first considering static factories.
Static Factory Methods
• The normal way for a class to allow a client to obtain an instance of
itself is to provide a public constructor. There is another technique
that should be a part of every programmer’s toolkit.
• A class can provide a public static factory method, which is simply a
static method that returns an instance of the class.
Static Factory Methods
Here’s a simple example from Boolean (the boxed primitive class for
the primitive type boolean). This method translates a boolean primitive
value into a Boolean object reference:
public static Boolean valueOf(boolean b) {
return b ? Boolean.TRUE : Boolean.FALSE;
}
A class can provide its clients with static factory methods instead of, or
in addition to, constructors. Providing a static factory method instead of
a public constructor has both advantages and disadvantages.
Advantages
First advantage of static factory methods is that, unlike
constructors, they have names.
• If the parameters to a constructor do not, in and of themselves,
describe the object being returned, a static factory with a well-chosen
name is easier to use and the resulting client code easier to read.
• Now let’s seen by an example.
Advantages
• Look at the following example.
• We have a RandomIntGenerator class that, as the name suggests,
generates random int numbers. Something like:
public class RandomIntGenerator {
private final int min;
private final int max;
public int next() {...}
}
Advantages
• Our generator takes a minimum and maximum and then generates
random numbers between those 2 values. Notice that the two
attributes are declared final so we have to initialize them either on
their declaration or in the class constructor. Let’s go with the
constructor:
public RandomIntGenerator(int min, int max) {
this.min = min;
this.max = max;
}
Advantages
• Now, we also want to give our clients the possibility to specify just a
minimum value and then generate random values between that
minimum and the max possible value for ints. So we add a second
constructor:
public RandomIntGenerator(int min) {
this.min = min;
this.max = Integer.MAX_VALUE;
}
Advantages
• So far so good, right? But in the same way that we provided a
constructor to just specify the minimum value, we want to do the
same for just the maximum. We’ll just add a third constructor like:
public RandomIntGenerator(int max) {
this.min = Integer.MIN_VALUE;
this.max = max;
}
• If you try that, you’ll get a compilation error that goes: Duplicate
method RandomIntGenerator(int) in type RandomIntGenerator.
What’s wrong?
Advantages
• Full script:
public class RandomIntGenerator {
private final int min;
private final int max;
public int next() {...}
public RandomIntGenerator(int min, int max) {
this.min = min;
this.max = max;
}
public RandomIntGenerator(int min) {
this.min = min;
this.max = Integer.MAX_VALUE;
}
/* Compilation error will be occurred. */
public RandomIntGenerator(int max) {
this.min = Integer.MIN_VALUE;
this.max = max;
}
}
Advantages
• The problem is that constructors, by definition, have no names. As
such, a class can only have one constructor with a given signature in
the same way that you can’t have two methods with the same
signature (same return type, name and parameters type).
• That is why when we tried to add the RandomIntGenerator(int
max) constructor we got that compilation error, because we already
had the RandomIntGenerator(int min) one.
Advantages
• Now let’s apply static factories to our RandomIntGenerator example, we could
get:
public class RandomIntGenerator {
private final int min;
private final int max;
// private constructor to non-institate class
private RandomIntGenerator(int min, int max) {
this.min = min;
this.max = max;
}
public static RandomIntGenerator between(int max, int min) {
return new RandomIntGenerator(min, max);
}
public static RandomIntGenerator biggerThan(int min) {
return new RandomIntGenerator(min, Integer.MAX_VALUE);
}
public static RandomIntGenerator smallerThan(int max) {
return new RandomIntGenerator(Integer.MIN_VALUE, max);
}
public int next() {...}
}
Advantages
• Note : How the constructor was made private to ensure that the
class is only instantiated through its public static factory methods.
• Also note how your intent is clearly expressed when you have a client
with RandomIntGenerator.between(10,20) instead of
new RandomIntGenerator(10,20)
• Point is clear, we replace the constructors with static factory methods
and carefully chosen names to highlight their differences.
Advantages
A second advantage of static factory methods is that, unlike
constructors, they are not required to create a new object each
time they’re invoked.
This is extremely useful when working with immutable classes to
provide constant objects for common used values and avoid creating
unnecessary duplicate objects. (You can refer avoid creating uncessary objects in this link
http://www.slideshare.net/mysky14/avoid-creating-unncessary-objects)
Advantages
public static Boolean valueOf(boolean b) {
return b ? Boolean.TRUE : Boolean.FALSE;
}
• The Boolean.valueOf code that I showed previously illustrates this
point perfectly. Notice that this static method returns either TRUE
or FALSE, both immutable Boolean objects.
• This technique is similar to the Flyweight pattern (I am promise I will post about this
pattern in near future, please don’t forget to following me at slideshare.). It can greatly improve
performance if equivalent objects are requested often, especially if
they are expensive to create.
Advantages
A third advantage of static factory methods is that, unlike
constructors, they can return an object of any subtype of their return
type.
• This gives you great flexibility in choosing the class of the returned
object.
• Moreover, you can hide implementation classes and have an interface-
based API (I am promise I will post about this interface-based framework in near future, please don’t forget to following me at slideshare.),
which is usually a really good idea.
• But I think this can be better seen by an example.
Advantages
• Look at the following example.
• Imagine that we now want to provide random generators not just for
integers but for other data-types like String, Double or Long. They are
all going to have a next() method that returns a random object of a
particular type, so we could start with an interface like:
public interface RandomGenerator<T> {
T next();
}
Advantages
• Our first implementation of the RandomIntGenerator now becomes:
class RandomIntGenerator implements RandomGenerator<Integer> {
private final int min;
private final int max;
RandomIntGenerator(int min, int max) {
this.min = min;
this.max = max;
}
public Integer next() {...}
}
Advantages
• We could also have a String generator:
class RandomStringGenerator implements RandomGenerator<String>
{
private final String prefix;
RandomStringGenerator(String prefix) {
this.prefix = prefix;
}
public String next() {...}
}
Advantages
• Notice how all the classes are declared package-private (default scope) and so
are their constructors. This means that no client outside of their package can
create instances of these generators. So what do we do? Tip: It starts with
“static” and ends with “methods”. Consider the following class:
public final class RandomGenerators {
// Suppresses default constructor, ensuring non-instantiability.
private RandomGenerators() {}
public static final RandomGenerator<Integer> getIntGenerator() {
return new RandomIntGenerator(Integer.MIN_VALUE, Integer.MAX_VALUE);
}
public static final RandomGenerator<String> getStringGenerator() {
return new RandomStringGenerator("");
}
}
Advantages
• RandomGenerators is just a noninstantiable utility class with nothing
else than static factory methods. Being on the same package as the
different generators this class can effectively access and instantiate
those classes. But here comes the interesting part.
• Note that the methods only return the RandomGenerator interface,
and that’s all the clients need really.
• If they get a RandomGenerator<Integer> they know that they can
call next() and get a random integer.
Advantages
Not only can the class of an object returned by a public static factory
method be nonpublic, but the class can vary from invocation to
invocation depending on the values of the parameters to the static
factory.
Any class that is a subtype of the declared return type is permissible.
The class of the returned object can also vary from release to release
for enhanced software maintainability and performance.
Advantages
• A fourth advantage of static factory methods is that they reduce
the verbosity of creating parameterized type instances.
• Have you ever had to write code like this?
Map<String, List<String>> map = new HashMap<String,List<String>>();
Advantages
• You are repeating the same parameters twice on the same line of
code. Wouldn’t it be nice if the right side of the assign could
be inferred from the left side?
• Well, with static factories it can. The following code is taken from
Guava’s Maps class:
public static <K, V> HashMap<K, V> newHashMap() {
return new HashMap<K, V>();
}
• So now our client code becomes:
Map<String, List<String>> map = Maps.newHashMap();
Advantages
• Pretty nice, isn’t it? This capability is known as Type inference. It’s
worth mentioning that Java 7 introduced type inference through the
use of the diamond operator. So if you’re using Java 7 you can write
the previous example as:
Map<String, List<String>> map = new HashMap<>();
• Unfortunately, the standard collection implementations such as
HashMap do not have factory methods as of release 1.6, but you can
put these methods in your own utility class.
• More importantly, you can provide such static factories in your
own parameterized classes.
Disadvantages
The main disadvantage of static factories is that classes without
public or protected constructors cannot be extended. But this might
be actually a good thing in some cases because it encourages
developers to favor composition over inheritance. (I am promise I will post about this
interface-based framework in near future, please don’t forget to following me at slideshare.)
• The same is true for nonpublic classes returned by public static factories.
For example, it is impossible to subclass any of the convenience
implementation classes in the Collections Framework.
• But I think this can be better seen by an our own example.
Disadvantages
• Suppose you have a class called Person:
class Person {
public static Person createWithFirstName(String firstName) {
return new Person(firstName, null, null);
}
// etc. - more factory methods
// private constructor
private Person(String firstName, String lastName, String nickname) { }
// useful method
public String getDisplayName() { }
}
Disadvantages
• It's all good and dandy. But now you also need a class
called Programmer, and you suddenly realize the programmers
are persons too!
• But all of a sudden, you can't just
class Programmer extends Person { }
• since Person doesn't have any public constructors.
• You can’t not subclassed which are not have public or protected
constructor.
Summary (Preface)
• In summary, static factory methods and public constructors both have
their uses, and it pays to understand their relative merits. Often static
factories are preferable, so avoid the reflex to provide public
constructors without first considering static factories.
References
• Effective Java – 2nd Edition (Joshua Bloch)
• http://stackoverflow.com/questions/19733789/static-factory-
disadvantage-over-constructor
• https://jlordiales.wordpress.com/2012/12/26/static-factory-methods-
vs-traditional-constructors/

More Related Content

What's hot

The Power of Composition (NDC Oslo 2020)
The Power of Composition (NDC Oslo 2020)The Power of Composition (NDC Oslo 2020)
The Power of Composition (NDC Oslo 2020)
Scott Wlaschin
 
Functional Error Handling with Cats
Functional Error Handling with CatsFunctional Error Handling with Cats
Functional Error Handling with Cats
Mark Canlas
 
Pertemuan 07 strategi proses
Pertemuan 07 strategi prosesPertemuan 07 strategi proses
Pertemuan 07 strategi proses
Pelita Bangsa University
 
Pengelolaan persediaan - Pert. 5.pptx
Pengelolaan persediaan - Pert. 5.pptxPengelolaan persediaan - Pert. 5.pptx
Pengelolaan persediaan - Pert. 5.pptx
BeritaDunia3
 
Algoritma dan Struktur Data - Object pada OOP
Algoritma dan Struktur Data - Object pada OOPAlgoritma dan Struktur Data - Object pada OOP
Algoritma dan Struktur Data - Object pada OOP
KuliahKita
 
Jurnal strategi pengembangan bisnis tanah kavling pada ksu bina usaha sejahtera
Jurnal strategi pengembangan bisnis tanah kavling pada ksu bina usaha sejahteraJurnal strategi pengembangan bisnis tanah kavling pada ksu bina usaha sejahtera
Jurnal strategi pengembangan bisnis tanah kavling pada ksu bina usaha sejahtera
Yusuf Darismah
 
Java Basics V3
Java Basics V3Java Basics V3
Java Basics V3
Sunil OS
 
Scala 3 by Example - Algebraic Data Types for Domain Driven Design - Part 2
Scala 3 by Example - Algebraic Data Types for Domain Driven Design - Part 2Scala 3 by Example - Algebraic Data Types for Domain Driven Design - Part 2
Scala 3 by Example - Algebraic Data Types for Domain Driven Design - Part 2
Philip Schwarz
 
Type Classes in Scala and Haskell
Type Classes in Scala and HaskellType Classes in Scala and Haskell
Type Classes in Scala and Haskell
Hermann Hueck
 
Mekanisme Pasar Dalam Islam (Ekonomi Syariah)
Mekanisme Pasar Dalam Islam (Ekonomi Syariah)Mekanisme Pasar Dalam Islam (Ekonomi Syariah)
Mekanisme Pasar Dalam Islam (Ekonomi Syariah)
kholifmuhaimin
 
ECONOMIC VALUE OF TIME.pptx
ECONOMIC VALUE OF TIME.pptxECONOMIC VALUE OF TIME.pptx
ECONOMIC VALUE OF TIME.pptx
RAJARYAN597243
 
Trends and future of C++: Evolving a systems language for performance - by Bj...
Trends and future of C++: Evolving a systems language for performance - by Bj...Trends and future of C++: Evolving a systems language for performance - by Bj...
Trends and future of C++: Evolving a systems language for performance - by Bj...
devstonez
 
Accurate and Efficient Refactoring Detection in Commit History
Accurate and Efficient Refactoring Detection in Commit HistoryAccurate and Efficient Refactoring Detection in Commit History
Accurate and Efficient Refactoring Detection in Commit History
Nikolaos Tsantalis
 
Towards Functional Programming through Hexagonal Architecture
Towards Functional Programming through Hexagonal ArchitectureTowards Functional Programming through Hexagonal Architecture
Towards Functional Programming through Hexagonal Architecture
CodelyTV
 
Groovy Programming Language
Groovy Programming LanguageGroovy Programming Language
Groovy Programming Language
Aniruddha Chakrabarti
 
Ii. pemilihan lokasi
Ii. pemilihan lokasiIi. pemilihan lokasi
Ii. pemilihan lokasi
Samin Grup
 
Bab 2 mengembangkan strategi dan rencana pemasaran
Bab 2 mengembangkan strategi dan rencana pemasaranBab 2 mengembangkan strategi dan rencana pemasaran
Bab 2 mengembangkan strategi dan rencana pemasaran
Judianto Nugroho
 
Functional Core and Imperative Shell - Game of Life Example - Haskell and Scala
Functional Core and Imperative Shell - Game of Life Example - Haskell and ScalaFunctional Core and Imperative Shell - Game of Life Example - Haskell and Scala
Functional Core and Imperative Shell - Game of Life Example - Haskell and Scala
Philip Schwarz
 

What's hot (20)

The Power of Composition (NDC Oslo 2020)
The Power of Composition (NDC Oslo 2020)The Power of Composition (NDC Oslo 2020)
The Power of Composition (NDC Oslo 2020)
 
Functional Error Handling with Cats
Functional Error Handling with CatsFunctional Error Handling with Cats
Functional Error Handling with Cats
 
Pertemuan 07 strategi proses
Pertemuan 07 strategi prosesPertemuan 07 strategi proses
Pertemuan 07 strategi proses
 
Pengelolaan persediaan - Pert. 5.pptx
Pengelolaan persediaan - Pert. 5.pptxPengelolaan persediaan - Pert. 5.pptx
Pengelolaan persediaan - Pert. 5.pptx
 
Algoritma dan Struktur Data - Object pada OOP
Algoritma dan Struktur Data - Object pada OOPAlgoritma dan Struktur Data - Object pada OOP
Algoritma dan Struktur Data - Object pada OOP
 
Jurnal strategi pengembangan bisnis tanah kavling pada ksu bina usaha sejahtera
Jurnal strategi pengembangan bisnis tanah kavling pada ksu bina usaha sejahteraJurnal strategi pengembangan bisnis tanah kavling pada ksu bina usaha sejahtera
Jurnal strategi pengembangan bisnis tanah kavling pada ksu bina usaha sejahtera
 
Java Basics V3
Java Basics V3Java Basics V3
Java Basics V3
 
Scala 3 by Example - Algebraic Data Types for Domain Driven Design - Part 2
Scala 3 by Example - Algebraic Data Types for Domain Driven Design - Part 2Scala 3 by Example - Algebraic Data Types for Domain Driven Design - Part 2
Scala 3 by Example - Algebraic Data Types for Domain Driven Design - Part 2
 
Type Classes in Scala and Haskell
Type Classes in Scala and HaskellType Classes in Scala and Haskell
Type Classes in Scala and Haskell
 
Pokok bahasan 1 kewirausahaan
Pokok bahasan 1 kewirausahaanPokok bahasan 1 kewirausahaan
Pokok bahasan 1 kewirausahaan
 
Mekanisme Pasar Dalam Islam (Ekonomi Syariah)
Mekanisme Pasar Dalam Islam (Ekonomi Syariah)Mekanisme Pasar Dalam Islam (Ekonomi Syariah)
Mekanisme Pasar Dalam Islam (Ekonomi Syariah)
 
Profil pengusaha
Profil pengusahaProfil pengusaha
Profil pengusaha
 
ECONOMIC VALUE OF TIME.pptx
ECONOMIC VALUE OF TIME.pptxECONOMIC VALUE OF TIME.pptx
ECONOMIC VALUE OF TIME.pptx
 
Trends and future of C++: Evolving a systems language for performance - by Bj...
Trends and future of C++: Evolving a systems language for performance - by Bj...Trends and future of C++: Evolving a systems language for performance - by Bj...
Trends and future of C++: Evolving a systems language for performance - by Bj...
 
Accurate and Efficient Refactoring Detection in Commit History
Accurate and Efficient Refactoring Detection in Commit HistoryAccurate and Efficient Refactoring Detection in Commit History
Accurate and Efficient Refactoring Detection in Commit History
 
Towards Functional Programming through Hexagonal Architecture
Towards Functional Programming through Hexagonal ArchitectureTowards Functional Programming through Hexagonal Architecture
Towards Functional Programming through Hexagonal Architecture
 
Groovy Programming Language
Groovy Programming LanguageGroovy Programming Language
Groovy Programming Language
 
Ii. pemilihan lokasi
Ii. pemilihan lokasiIi. pemilihan lokasi
Ii. pemilihan lokasi
 
Bab 2 mengembangkan strategi dan rencana pemasaran
Bab 2 mengembangkan strategi dan rencana pemasaranBab 2 mengembangkan strategi dan rencana pemasaran
Bab 2 mengembangkan strategi dan rencana pemasaran
 
Functional Core and Imperative Shell - Game of Life Example - Haskell and Scala
Functional Core and Imperative Shell - Game of Life Example - Haskell and ScalaFunctional Core and Imperative Shell - Game of Life Example - Haskell and Scala
Functional Core and Imperative Shell - Game of Life Example - Haskell and Scala
 

Viewers also liked

Constructor and desturctor
Constructor and desturctorConstructor and desturctor
Constructor and desturctorSomnath Kulkarni
 
Builder pattern vs constructor
Builder pattern vs constructorBuilder pattern vs constructor
Builder pattern vs constructor
Liviu Tudor
 
04. constructor & destructor
04. constructor & destructor04. constructor & destructor
04. constructor & destructorHaresh Jaiswal
 
Tut Constructor
Tut ConstructorTut Constructor
Constructor & destructor
Constructor & destructorConstructor & destructor
Constructor & destructor
Saharsh Anand
 
constructor & destructor in cpp
constructor & destructor in cppconstructor & destructor in cpp
constructor & destructor in cpp
gourav kottawar
 
Constructors and destructors
Constructors and destructorsConstructors and destructors
Constructors and destructors
Nilesh Dalvi
 
Constructor & Destructor
Constructor & DestructorConstructor & Destructor
Constructor & Destructor
KV(AFS) Utarlai, Barmer (Rajasthan)
 
Constructor and destructor in c++
Constructor and destructor in c++Constructor and destructor in c++
Constructor and destructor in c++
Learn By Watch
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
Hitesh Kumar
 
Constructor and Destructor
Constructor and DestructorConstructor and Destructor
Constructor and DestructorKamal Acharya
 
Constructor ppt
Constructor pptConstructor ppt
Constructor ppt
Vinod Kumar
 

Viewers also liked (13)

Constructor and desturctor
Constructor and desturctorConstructor and desturctor
Constructor and desturctor
 
Builder pattern vs constructor
Builder pattern vs constructorBuilder pattern vs constructor
Builder pattern vs constructor
 
04. constructor & destructor
04. constructor & destructor04. constructor & destructor
04. constructor & destructor
 
Tut Constructor
Tut ConstructorTut Constructor
Tut Constructor
 
Constructor & destructor
Constructor & destructorConstructor & destructor
Constructor & destructor
 
constructor & destructor in cpp
constructor & destructor in cppconstructor & destructor in cpp
constructor & destructor in cpp
 
Constructors & destructors
Constructors & destructorsConstructors & destructors
Constructors & destructors
 
Constructors and destructors
Constructors and destructorsConstructors and destructors
Constructors and destructors
 
Constructor & Destructor
Constructor & DestructorConstructor & Destructor
Constructor & Destructor
 
Constructor and destructor in c++
Constructor and destructor in c++Constructor and destructor in c++
Constructor and destructor in c++
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
Constructor and Destructor
Constructor and DestructorConstructor and Destructor
Constructor and Destructor
 
Constructor ppt
Constructor pptConstructor ppt
Constructor ppt
 

Similar to Java Static Factory Methods

Software Design Patterns
Software Design PatternsSoftware Design Patterns
Software Design Patterns
Pankhuree Srivastava
 
Desing pattern prototype-Factory Method, Prototype and Builder
Desing pattern prototype-Factory Method, Prototype and Builder Desing pattern prototype-Factory Method, Prototype and Builder
Desing pattern prototype-Factory Method, Prototype and Builder
paramisoft
 
Creating and destroying objects
Creating and destroying objectsCreating and destroying objects
Creating and destroying objects
Sandeep Chawla
 
Effective Java - Chapter 2: Creating and Destroying Objects
Effective Java - Chapter 2: Creating and Destroying ObjectsEffective Java - Chapter 2: Creating and Destroying Objects
Effective Java - Chapter 2: Creating and Destroying Objects
İbrahim Kürce
 
Abstract factory
Abstract factoryAbstract factory
Abstract factory
Muthukumar P
 
Lecture 1 interfaces and polymorphism
Lecture 1    interfaces and polymorphismLecture 1    interfaces and polymorphism
Lecture 1 interfaces and polymorphism
Nada G.Youssef
 
CiIC4010-chapter-2-f17
CiIC4010-chapter-2-f17CiIC4010-chapter-2-f17
CiIC4010-chapter-2-f17
BienvenidoVelezUPR
 
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
Ravi Bhadauria
 
Dependency injection using dagger2
Dependency injection using dagger2Dependency injection using dagger2
Dependency injection using dagger2
Javad Hashemi
 
TDD And Refactoring
TDD And RefactoringTDD And Refactoring
TDD And Refactoring
Naresh Jain
 
2CPP18 - Modifiers
2CPP18 - Modifiers2CPP18 - Modifiers
2CPP18 - Modifiers
Michael Heron
 
Ej Chpt#4 Final
Ej Chpt#4 FinalEj Chpt#4 Final
Ej Chpt#4 Final
Chandan Benjaram
 
CDI: How do I ?
CDI: How do I ?CDI: How do I ?
CDI: How do I ?
Antonio Goncalves
 
Javascript Common Design Patterns
Javascript Common Design PatternsJavascript Common Design Patterns
Javascript Common Design Patterns
Pham Huy Tung
 
Constructor destructor.ppt
Constructor destructor.pptConstructor destructor.ppt
Constructor destructor.ppt
Karthik Sekar
 
Effective java
Effective javaEffective java
Effective java
Emprovise
 
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
Roman Tsypuk
 
Unit testing - A&BP CC
Unit testing - A&BP CCUnit testing - A&BP CC
Unit testing - A&BP CC
JWORKS powered by Ordina
 
Intro to programing with java-lecture 3
Intro to programing with java-lecture 3Intro to programing with java-lecture 3
Intro to programing with java-lecture 3
Mohamed Essam
 

Similar to Java Static Factory Methods (20)

Software Design Patterns
Software Design PatternsSoftware Design Patterns
Software Design Patterns
 
Desing pattern prototype-Factory Method, Prototype and Builder
Desing pattern prototype-Factory Method, Prototype and Builder Desing pattern prototype-Factory Method, Prototype and Builder
Desing pattern prototype-Factory Method, Prototype and Builder
 
Creating and destroying objects
Creating and destroying objectsCreating and destroying objects
Creating and destroying objects
 
Effective Java - Chapter 2: Creating and Destroying Objects
Effective Java - Chapter 2: Creating and Destroying ObjectsEffective Java - Chapter 2: Creating and Destroying Objects
Effective Java - Chapter 2: Creating and Destroying Objects
 
Abstract factory
Abstract factoryAbstract factory
Abstract factory
 
Lecture 1 interfaces and polymorphism
Lecture 1    interfaces and polymorphismLecture 1    interfaces and polymorphism
Lecture 1 interfaces and polymorphism
 
CiIC4010-chapter-2-f17
CiIC4010-chapter-2-f17CiIC4010-chapter-2-f17
CiIC4010-chapter-2-f17
 
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
 
Trigger
TriggerTrigger
Trigger
 
Dependency injection using dagger2
Dependency injection using dagger2Dependency injection using dagger2
Dependency injection using dagger2
 
TDD And Refactoring
TDD And RefactoringTDD And Refactoring
TDD And Refactoring
 
2CPP18 - Modifiers
2CPP18 - Modifiers2CPP18 - Modifiers
2CPP18 - Modifiers
 
Ej Chpt#4 Final
Ej Chpt#4 FinalEj Chpt#4 Final
Ej Chpt#4 Final
 
CDI: How do I ?
CDI: How do I ?CDI: How do I ?
CDI: How do I ?
 
Javascript Common Design Patterns
Javascript Common Design PatternsJavascript Common Design Patterns
Javascript Common Design Patterns
 
Constructor destructor.ppt
Constructor destructor.pptConstructor destructor.ppt
Constructor destructor.ppt
 
Effective java
Effective javaEffective java
Effective java
 
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
 
Unit testing - A&BP CC
Unit testing - A&BP CCUnit testing - A&BP CC
Unit testing - A&BP CC
 
Intro to programing with java-lecture 3
Intro to programing with java-lecture 3Intro to programing with java-lecture 3
Intro to programing with java-lecture 3
 

More from Ye Win

001 public speaking
001 public speaking001 public speaking
001 public speaking
Ye Win
 
My ridiculous productivity secret (i'm using it now)
My ridiculous productivity secret (i'm using it now)My ridiculous productivity secret (i'm using it now)
My ridiculous productivity secret (i'm using it now)
Ye Win
 
Mastering google search (i'm using it now)
Mastering google search (i'm using it now)Mastering google search (i'm using it now)
Mastering google search (i'm using it now)
Ye Win
 
Avoid creating unncessary objects
Avoid creating unncessary objectsAvoid creating unncessary objects
Avoid creating unncessary objects
Ye Win
 
11 rules for programmer should live by
11 rules for programmer should live by11 rules for programmer should live by
11 rules for programmer should live by
Ye Win
 
Object+oriented+programming+in+java
Object+oriented+programming+in+javaObject+oriented+programming+in+java
Object+oriented+programming+in+java
Ye Win
 
Spring Transaction Management
Spring Transaction ManagementSpring Transaction Management
Spring Transaction Management
Ye Win
 

More from Ye Win (7)

001 public speaking
001 public speaking001 public speaking
001 public speaking
 
My ridiculous productivity secret (i'm using it now)
My ridiculous productivity secret (i'm using it now)My ridiculous productivity secret (i'm using it now)
My ridiculous productivity secret (i'm using it now)
 
Mastering google search (i'm using it now)
Mastering google search (i'm using it now)Mastering google search (i'm using it now)
Mastering google search (i'm using it now)
 
Avoid creating unncessary objects
Avoid creating unncessary objectsAvoid creating unncessary objects
Avoid creating unncessary objects
 
11 rules for programmer should live by
11 rules for programmer should live by11 rules for programmer should live by
11 rules for programmer should live by
 
Object+oriented+programming+in+java
Object+oriented+programming+in+javaObject+oriented+programming+in+java
Object+oriented+programming+in+java
 
Spring Transaction Management
Spring Transaction ManagementSpring Transaction Management
Spring Transaction Management
 

Recently uploaded

SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfSAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
Peter Spielvogel
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Thierry Lestable
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
sonjaschweigert1
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
Pierluigi Pugliese
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 
Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
RinaMondal9
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 

Recently uploaded (20)

SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfSAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 
Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 

Java Static Factory Methods

  • 1. JAVA CONSIDER STATIC FACTORY METHODS INSTEAD OF CONSTRUCTORS Ye Win 11/21/2015
  • 2. Contents • Preface (Summary) • Static Factory Methods • Advantages • Disadvantages • Summary (Preface)
  • 3. Preface (Summary) In preface, static factory methods and public constructors both have their uses, and it pays to understand their relative merits. Often static factories are preferable, so avoid the reflex to provide public constructors without first considering static factories.
  • 4. Static Factory Methods • The normal way for a class to allow a client to obtain an instance of itself is to provide a public constructor. There is another technique that should be a part of every programmer’s toolkit. • A class can provide a public static factory method, which is simply a static method that returns an instance of the class.
  • 5. Static Factory Methods Here’s a simple example from Boolean (the boxed primitive class for the primitive type boolean). This method translates a boolean primitive value into a Boolean object reference: public static Boolean valueOf(boolean b) { return b ? Boolean.TRUE : Boolean.FALSE; } A class can provide its clients with static factory methods instead of, or in addition to, constructors. Providing a static factory method instead of a public constructor has both advantages and disadvantages.
  • 6. Advantages First advantage of static factory methods is that, unlike constructors, they have names. • If the parameters to a constructor do not, in and of themselves, describe the object being returned, a static factory with a well-chosen name is easier to use and the resulting client code easier to read. • Now let’s seen by an example.
  • 7. Advantages • Look at the following example. • We have a RandomIntGenerator class that, as the name suggests, generates random int numbers. Something like: public class RandomIntGenerator { private final int min; private final int max; public int next() {...} }
  • 8. Advantages • Our generator takes a minimum and maximum and then generates random numbers between those 2 values. Notice that the two attributes are declared final so we have to initialize them either on their declaration or in the class constructor. Let’s go with the constructor: public RandomIntGenerator(int min, int max) { this.min = min; this.max = max; }
  • 9. Advantages • Now, we also want to give our clients the possibility to specify just a minimum value and then generate random values between that minimum and the max possible value for ints. So we add a second constructor: public RandomIntGenerator(int min) { this.min = min; this.max = Integer.MAX_VALUE; }
  • 10. Advantages • So far so good, right? But in the same way that we provided a constructor to just specify the minimum value, we want to do the same for just the maximum. We’ll just add a third constructor like: public RandomIntGenerator(int max) { this.min = Integer.MIN_VALUE; this.max = max; } • If you try that, you’ll get a compilation error that goes: Duplicate method RandomIntGenerator(int) in type RandomIntGenerator. What’s wrong?
  • 11. Advantages • Full script: public class RandomIntGenerator { private final int min; private final int max; public int next() {...} public RandomIntGenerator(int min, int max) { this.min = min; this.max = max; } public RandomIntGenerator(int min) { this.min = min; this.max = Integer.MAX_VALUE; } /* Compilation error will be occurred. */ public RandomIntGenerator(int max) { this.min = Integer.MIN_VALUE; this.max = max; } }
  • 12. Advantages • The problem is that constructors, by definition, have no names. As such, a class can only have one constructor with a given signature in the same way that you can’t have two methods with the same signature (same return type, name and parameters type). • That is why when we tried to add the RandomIntGenerator(int max) constructor we got that compilation error, because we already had the RandomIntGenerator(int min) one.
  • 13. Advantages • Now let’s apply static factories to our RandomIntGenerator example, we could get: public class RandomIntGenerator { private final int min; private final int max; // private constructor to non-institate class private RandomIntGenerator(int min, int max) { this.min = min; this.max = max; } public static RandomIntGenerator between(int max, int min) { return new RandomIntGenerator(min, max); } public static RandomIntGenerator biggerThan(int min) { return new RandomIntGenerator(min, Integer.MAX_VALUE); } public static RandomIntGenerator smallerThan(int max) { return new RandomIntGenerator(Integer.MIN_VALUE, max); } public int next() {...} }
  • 14. Advantages • Note : How the constructor was made private to ensure that the class is only instantiated through its public static factory methods. • Also note how your intent is clearly expressed when you have a client with RandomIntGenerator.between(10,20) instead of new RandomIntGenerator(10,20) • Point is clear, we replace the constructors with static factory methods and carefully chosen names to highlight their differences.
  • 15. Advantages A second advantage of static factory methods is that, unlike constructors, they are not required to create a new object each time they’re invoked. This is extremely useful when working with immutable classes to provide constant objects for common used values and avoid creating unnecessary duplicate objects. (You can refer avoid creating uncessary objects in this link http://www.slideshare.net/mysky14/avoid-creating-unncessary-objects)
  • 16. Advantages public static Boolean valueOf(boolean b) { return b ? Boolean.TRUE : Boolean.FALSE; } • The Boolean.valueOf code that I showed previously illustrates this point perfectly. Notice that this static method returns either TRUE or FALSE, both immutable Boolean objects. • This technique is similar to the Flyweight pattern (I am promise I will post about this pattern in near future, please don’t forget to following me at slideshare.). It can greatly improve performance if equivalent objects are requested often, especially if they are expensive to create.
  • 17. Advantages A third advantage of static factory methods is that, unlike constructors, they can return an object of any subtype of their return type. • This gives you great flexibility in choosing the class of the returned object. • Moreover, you can hide implementation classes and have an interface- based API (I am promise I will post about this interface-based framework in near future, please don’t forget to following me at slideshare.), which is usually a really good idea. • But I think this can be better seen by an example.
  • 18. Advantages • Look at the following example. • Imagine that we now want to provide random generators not just for integers but for other data-types like String, Double or Long. They are all going to have a next() method that returns a random object of a particular type, so we could start with an interface like: public interface RandomGenerator<T> { T next(); }
  • 19. Advantages • Our first implementation of the RandomIntGenerator now becomes: class RandomIntGenerator implements RandomGenerator<Integer> { private final int min; private final int max; RandomIntGenerator(int min, int max) { this.min = min; this.max = max; } public Integer next() {...} }
  • 20. Advantages • We could also have a String generator: class RandomStringGenerator implements RandomGenerator<String> { private final String prefix; RandomStringGenerator(String prefix) { this.prefix = prefix; } public String next() {...} }
  • 21. Advantages • Notice how all the classes are declared package-private (default scope) and so are their constructors. This means that no client outside of their package can create instances of these generators. So what do we do? Tip: It starts with “static” and ends with “methods”. Consider the following class: public final class RandomGenerators { // Suppresses default constructor, ensuring non-instantiability. private RandomGenerators() {} public static final RandomGenerator<Integer> getIntGenerator() { return new RandomIntGenerator(Integer.MIN_VALUE, Integer.MAX_VALUE); } public static final RandomGenerator<String> getStringGenerator() { return new RandomStringGenerator(""); } }
  • 22. Advantages • RandomGenerators is just a noninstantiable utility class with nothing else than static factory methods. Being on the same package as the different generators this class can effectively access and instantiate those classes. But here comes the interesting part. • Note that the methods only return the RandomGenerator interface, and that’s all the clients need really. • If they get a RandomGenerator<Integer> they know that they can call next() and get a random integer.
  • 23. Advantages Not only can the class of an object returned by a public static factory method be nonpublic, but the class can vary from invocation to invocation depending on the values of the parameters to the static factory. Any class that is a subtype of the declared return type is permissible. The class of the returned object can also vary from release to release for enhanced software maintainability and performance.
  • 24. Advantages • A fourth advantage of static factory methods is that they reduce the verbosity of creating parameterized type instances. • Have you ever had to write code like this? Map<String, List<String>> map = new HashMap<String,List<String>>();
  • 25. Advantages • You are repeating the same parameters twice on the same line of code. Wouldn’t it be nice if the right side of the assign could be inferred from the left side? • Well, with static factories it can. The following code is taken from Guava’s Maps class: public static <K, V> HashMap<K, V> newHashMap() { return new HashMap<K, V>(); } • So now our client code becomes: Map<String, List<String>> map = Maps.newHashMap();
  • 26. Advantages • Pretty nice, isn’t it? This capability is known as Type inference. It’s worth mentioning that Java 7 introduced type inference through the use of the diamond operator. So if you’re using Java 7 you can write the previous example as: Map<String, List<String>> map = new HashMap<>(); • Unfortunately, the standard collection implementations such as HashMap do not have factory methods as of release 1.6, but you can put these methods in your own utility class. • More importantly, you can provide such static factories in your own parameterized classes.
  • 27. Disadvantages The main disadvantage of static factories is that classes without public or protected constructors cannot be extended. But this might be actually a good thing in some cases because it encourages developers to favor composition over inheritance. (I am promise I will post about this interface-based framework in near future, please don’t forget to following me at slideshare.) • The same is true for nonpublic classes returned by public static factories. For example, it is impossible to subclass any of the convenience implementation classes in the Collections Framework. • But I think this can be better seen by an our own example.
  • 28. Disadvantages • Suppose you have a class called Person: class Person { public static Person createWithFirstName(String firstName) { return new Person(firstName, null, null); } // etc. - more factory methods // private constructor private Person(String firstName, String lastName, String nickname) { } // useful method public String getDisplayName() { } }
  • 29. Disadvantages • It's all good and dandy. But now you also need a class called Programmer, and you suddenly realize the programmers are persons too! • But all of a sudden, you can't just class Programmer extends Person { } • since Person doesn't have any public constructors. • You can’t not subclassed which are not have public or protected constructor.
  • 30. Summary (Preface) • In summary, static factory methods and public constructors both have their uses, and it pays to understand their relative merits. Often static factories are preferable, so avoid the reflex to provide public constructors without first considering static factories.
  • 31.
  • 32. References • Effective Java – 2nd Edition (Joshua Bloch) • http://stackoverflow.com/questions/19733789/static-factory- disadvantage-over-constructor • https://jlordiales.wordpress.com/2012/12/26/static-factory-methods- vs-traditional-constructors/