Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possibilities of creating immutable class in Java

what are possibilities of creating immutable bean in Java. For example I have immutable class Person. What's a good way to create instance and fill private fields. Public constructor doesn't seems good to me because of a lot input parameters will occure as class will grow in rest of application. Thank you for any suggestions.

public class Person {

private String firstName;
private String lastName;
private List<Address> addresses;
private List<Phone> phones;

public List<Address> getAddresses() {
    return Collections.unmodifiableList(addresses);
}

public String getFirstName() {
    return firstName;
}

public String getLastName() {
    return lastName;
}

public List<Phone> getPhones() {
    return Collections.unmodifiableList(phones);
}
}

EDIT: Specify question more precisely.

like image 594
michal.kreuzman Avatar asked May 08 '26 22:05

michal.kreuzman


1 Answers

You could use the builder pattern.

public class PersonBuilder {
  private String firstName;
  // and others...

  public PersonBuilder() {
    // no arguments necessary for the builder
  }

  public PersonBuilder firstName(String firstName) {
    this.firstName = firstName;
    return this;
  }

  public Person build() {
    // here (or in the Person constructor) you could validate the data
    return new Person(firstName, ...);
  }
}

You can then use it like this:

Person p = new PersonBuilder.firstName("Foo").build();

At first sight it might look more complex than a simple constructor with tons of parameters (and it probably is), but there are a few significant advantages:

  • You don't need to specify values that you want to keep at the default values
  • You can extend the Person class and the builder without having to declare multiple constructors or needing to rewrite every code that creates a Person: simply add methods to the builder, if someone doesn't call them, it doesn't matter.
  • You could pass around the builder object to allow different pieces of code to set different parameters of the Person.
  • You can use the builder to create multiple similar Person objects, which can be useful for unit tests, for example:

    PersonBuilder builder = new PersonBuilder().firstName("Foo").addAddress(new Address(...));
    Person fooBar = builder.lastName("Bar").build();
    Person fooBaz = builder.lastName("Baz").build();
    assertFalse(fooBar.equals(fooBaz));
    
like image 57
Joachim Sauer Avatar answered May 11 '26 15:05

Joachim Sauer