What is Telescoping Constructor Pattern?
In Java, there is no support for default values for constructor parameters. As a workaround, a technique called “Telescoping constructor” is often used. A class has multiple constructors, where each constructor calls a more specific constructor in the hierarchy, which has more parameters than itself, providing default values for the extra parameters.

We’ve all at some point encountered a class with a list of constructors where each addition adds a new option parameter

Pizza(int size) { ... }        
Pizza(int size, boolean cheese) { ... }    
Pizza(int size, boolean cheese, boolean pepperoni) { ... }    
Pizza(int size, boolean cheese, boolean pepperoni, boolean bacon) { ... }

Disadvantage
This is called the Telescoping Constructor Pattern. The problem with this pattern is that once constructors are 4 or 5 parameters long it becomes difficult to remember the required order of the parameters as well as what particular constructor you might want in a given situation.

One alternative you have to the Telescoping Constructor Pattern is the JavaBean Pattern where you call a constructor with the mandatory parameters and then call any optional setters after:

Pizza pizza = new Pizza(12);
pizza.setCheese(true);
pizza.setPepperoni(true);
pizza.setBacon(true);

The problem here is that because the object is created over several calls it may be in an inconsistent state partway through its construction. This also requires a lot of extra effort to ensure thread safety.

The better alternative is to use the Builder Pattern.

public class Pizza {
  private int size;
  private boolean cheese;
  private boolean pepperoni;
  private boolean bacon;

  public static class Builder {
    //required
    private final int size;

    //optional
    private boolean cheese = false;
    private boolean pepperoni = false;
    private boolean bacon = false;

    public Builder(int size) {
      this.size = size;
    }

    public Builder cheese(boolean value) {
      cheese = value;
      return this;
    }

    public Builder pepperoni(boolean value) {
      pepperoni = value;
      return this;
    }

    public Builder bacon(boolean value) {
      bacon = value;
      return this;
    }

    public Pizza build() {
      return new Pizza(this);
    }
  }

  private Pizza(Builder builder) {
    size = builder.size;
    cheese = builder.cheese;
    pepperoni = builder.pepperoni;
    bacon = builder.bacon;
  }
}

Note that Pizza is immutable and that parameter values are all in a single location. Because the Builder’s setter methods return the Builder object they are able to be chained.

Pizza pizza = new Pizza.Builder(12)
                       .cheese(true)
                       .pepperoni(true)
                       .bacon(true)
                       .build();

This results in code that is easy to write and very easy to read and understand. In this example, the build method could be modified to check parameters after they have been copied from the builder to the Pizza object and throw an IllegalStateException if an invalid parameter value has been supplied. This pattern is flexible and it is easy to add more parameters to it in the future. It is really only useful if you are going to have more than 4 or 5 parameters for a constructor. That said, it might be worthwhile in the first place if you suspect you may be adding more parameters in the future.

Factory Patterns vs Builder Pattern
Consider a restaurant. The creation of “today’s meal” is a factory pattern, because you tell the kitchen “get me today’s meal” and the kitchen (factory) decides what object to generate, based on hidden criteria.

The builder appears if you order a custom pizza. In this case, the waiter tells the chef (builder) “I need a pizza; add cheese, onions and bacon to it!” Thus, the builder exposes the attributes the generated object should have, but hides how to set them.

 Calendar.getInstance().getActualMaximum(Calendar.DAY_OF_MONTH);

The above returns actual maximum for current month. For example it is February of leap year now, so it returns 29.

And to get last day as Date object:

Calendar cal = Calendar.getInstance();
cal.set(Calendar.DATE, cal.getActualMaximum(Calendar.DATE));

Date lastDayOfMonth = cal.getTime();

java beans = default constructor + getters + setters

You want to model a person and in your model each person must have a name and surname.
In java beans convention you would have to
1) create a person and then
2) populate it with name and surname.

But in between 1 and 2 you have existing object that has inconsistent state, its a person without a name. in this trivial example it looks as a exaggeration but if you have a complex system it starts to matter.

Let’s see simple example

class Person {
   private String firstName;
   private String lastName;
   public String getFirstName() {return firstName;}
   public void setFirstName(String firstName) {this.firstName = firstName;}
   public String getLastName() {return lastName;}
   public void setLastName(String lastName) {this.lastName = lastName;}
}

The code creates instance of Person an initiates it:

Person president = new Person();
p.setFirstName("George");
p.setLastName("Bush");

From the above line of code the below can be incurred

  1. This means that the object is in constant state when all 3 lines are completed and in not consistent state before that.
  2. The object is indeed mutable: values that it calls may be changed by invoking of setter.

Our class Person is not thread-safe and therefore we cannot use it directly in multi threaded environment without thinking about syncrhonization.

Here is an example. Several years ago Barak Obama became the President of the US. How can we express this in code?

p.setFirstName("Barak");
p.setLastName("Obama");

In mutlti threaded environment the president object is in wrong state when when setFristName() had already completed and setLastName() has not called yet because the object contains “Barak Bush” that is obviously wrong.

What is the solution? Let’s make `Person immutable:

class Person {
   private final String firstName;
   private final String lastName;
   Person(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
   }

   public String getFirstName() {return firstName;}
   public String getLastName() {return lastName;}
}

As you can see there is not way to change either first or last name stored in object. The fields a final and do not have setters. So, our example looks like:

Person president = new Person("George", "Bush"); 
// elections..... 
president = new Person("Barak", "Obama");

Since Person is immutable we cannot re-use the old instance of Person and change its attribute. We have to create the new instance instead. If president is volatile reference assignment is atomic and therefore the code is thread safe.

Disadvantage
The problem of constructors is that they are not flexible. Our example has only 2 parameters. But think about real world when class Person has probably 20 or more field. In this case creating of such object is pretty verbose.

Moreover some fields can be optional. In this case you will probably want to create several overloaded constructors with different number of parameters. To avoid dupplicate assignemnt code it is common technique to use so called telescopic constructors

Few FAQ’s
Is using JavaBeans for data storage a bad practice and should be avoided, or is it perfectly safe?
No, is not a bad practice. Is not perfectly safe either. Depends on the situation.

The problem with mutable objects ( not with JavaBeans per se ) is using different threads to access them.

You have to synchronize the access to avoid one thread modify the object while other is accessing it.

Immutable objects doesn’t have this problem, because, .. well they can’t change, and thus, you don’t have to synchronize anything.

To make sure an object is immutable you have to declare your attributes as final.

class MyBean  {
    private final int i;
}

If you want to assign a reasonable value to MyBean.i you have to specify it in the constructor:

public MyBean( int i ) {
     this.i = i;
 }

Since the variable is final, you can’t use a setter. You can just provide a getter.

This is perfectly thread-safe and the best is, you don’t have to synchronize the access, because if two threads try to get the value of i they both will always see the value that was assigned on instantiation, you don’t have to synchronize anything.

Is not bad practice or good practice. Must of us have to work with a single thread, even in multithread environments like servlets.

How to set and change values if Immutable Objects
The Solution is to create immutable beans, and still provide a
bunch of setters is using Builders like

Setting Value

Employee e = new EmployeeBuilder()
                  .setName("Oscar")
                  .setLastName("Reyes")
                  .setAge(0x1F)
                  .setEmployeeId("123forme")
                  .build(); 

Which looks pretty similar to the regular setXyz used in regular beans with the benefit of using immutable data.

If you need to change one value, you can use a class method

Employee e = Employee.withName( e, "Mr. Oscar");

Which takes the existing object, and copy all the values, and set’s a new one….

public static EmployeeWithName( Employee e , String newName ){
      return new Employee( newName, e.lastName, e.age, e.employeeId );
}

But again, in a single thread model is perfectly safe to use getters/setters.