patternjavaMinor
Constructor Chaining in Java
Viewed 0 times
javaconstructorchaining
Problem
When creating multiple constructors, I usually do the following;
However, I can also do it this way;
Is there any actual difference here? Which would be better to use when coding?
public ConstructorName(int count)
{
this(count, 0);
}
public ConstructorName(String count)
{
this(Integer.parseInt(count), 0);
}
public ConstructorName(int count, int other)
{
// Do something here
}However, I can also do it this way;
public ConstructorName(String count)
{
this(Integer.parseInt(count)); // Chain to the constructor that just takes a number
}
public ConstructorName(int count)
{
this(count, 0);
}
public ConstructorName(int count, int other)
{
// Do something here
}Is there any actual difference here? Which would be better to use when coding?
Solution
If there is more than one way to construct an instance, then static factory methods backed by one private constructor, can really help readability, since they can be named differently.
If it is really about setting some properties and not others, then the Builder pattern can be what you want.
Both of these approaches also allow for hiding which implementation class is really returned. Our
Range halfOpen = Range.largerThan(5);
Range closed = Range.between(7, 12);If it is really about setting some properties and not others, then the Builder pattern can be what you want.
Person john = Person.named("John")
.lastName("Lennon")
.gender(Male)
.yearOfBirth(1940)
.build();Both of these approaches also allow for hiding which implementation class is really returned. Our
Person instance may be an instance of subclass Man, and the half open Range may be an instance of HalfOpenRange. Both methods allow returning a cached instance, rather than an actual new instance.Code Snippets
Range halfOpen = Range.largerThan(5);
Range closed = Range.between(7, 12);Person john = Person.named("John")
.lastName("Lennon")
.gender(Male)
.yearOfBirth(1940)
.build();Context
StackExchange Code Review Q#29142, answer score: 2
Revisions (0)
No revisions yet.