Google

Apr 16, 2014

How to create immutable objects more elegantly in Java?

It is a best practice to create immutable objects where possible because they are inherently thread-safe as you cannot modify them once created, and makes your code easier to debug.

Here is an approach to create immutable objects in Java with the builder design pattern.

The Driver POJO with the Builder as the static inner class.


package com.java8.examples;

public class Driver {
 enum SEX {
  MALE, FEMALE
 }

 private String name;
 private int age;
 private SEX sex;

 private Driver(Builder builder) {
        this.name = builder.name;
        this.age = builder.age;
        this.sex = builder.sex;
 }

 
 @Override
 public String toString() {
  return "Person [name=" + name + ", age=" + age + ", sex=" + sex + "]";
 }

 //builder design pattern
 public static class Builder {
  private String name;
  private int age;
  private SEX sex;

  public Builder name(String name) {
   this.name = name;
   return this;
  }

  public Builder age(int age) {
   this.age = age;
   return this;
  }

  public Builder sex(SEX sex) {
   this.sex = sex;
   return this;
  }

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


Now, here is how you elegantly construct the Driver object


package com.java8.examples;

public class DriverTest {
 
 public static void main(String[] args) {
  
   //immutable driver1 as Driver class has not setter methods
   Driver driver1 = new Driver.Builder()
             .name("John")
             .age(18)
             .sex(Driver.SEX.MALE)
             .build();
      
   System.out.println(driver1);
   
 }

}


Another example to create a list of drivers

package com.java8.examples;

import java.util.Arrays;
import java.util.List;

public class DriverTest {
 
 public static void main(String[] args) {
  List<driver> drivers = Arrays.asList (
  
   new Driver.Builder()
             .name("John")
             .age(18)
             .sex(Driver.SEX.MALE)
             .build(),
             
   new Driver.Builder()
             .name("Jessica")
             .age(24)
             .sex(Driver.SEX.FEMALE)
             .build(),
             
   new Driver.Builder()
             .name("Samantha")
             .age(36)
             .sex(Driver.SEX.FEMALE)
             .build()
                
   );   
    
 }

}



Another good practical example is Performing financial calculations with BigDecimal and Builder design pattern.

Labels:

1 Comments:

Anonymous Anonymous said...

line 9 from Another example to create a list of drivers should read
List drivers = Arrays.asList (

4:09 AM, April 30, 2014  

Post a Comment

Subscribe to Post Comments [Atom]

<< Home