1

Is it important to define required attributes on the builder as final ? ( code performance )

This is an example illustrating my question :

public class User {
private final String firstName; // required
private final String lastName; // required
private final int age; // optional
private final String phone; // optional
private final String address; // optional

private User(UserBuilder builder) {
    this.firstName = builder.firstName;
    this.lastName = builder.lastName;
    this.age = builder.age;
    this.phone = builder.phone;
    this.address = builder.address;
}

public String getFirstName() {
    return firstName;
}

public String getLastName() {
    return lastName;
}

public int getAge() {
    return age;
}

public String getPhone() {
    return phone;
}

public String getAddress() {
    return address;
}

public static class UserBuilder {
    private final String firstName; // required
    private final String lastName;  // required
    private int age;
    private String phone;
    private String address;

    public UserBuilder(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

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

    public UserBuilder phone(String phone) {
        this.phone = phone;
        return this;
    }

    public UserBuilder address(String address) {
        this.address = address;
        return this;
    }

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

}
}
MCHAppy
  • 1,012
  • 9
  • 15
  • No. It is not. Required attributes should be checked in `build()`. As should any other requirements. – Boris the Spider Oct 26 '14 at 10:06
  • Yes , i know required attributes should be in the constructor of the UserBuilder class , but defining required attributes as final does not effect code performance ?? – MCHAppy Oct 26 '14 at 10:11
  • No, they should not! A builder should have a **no args** constructor. The state of the builder should be checked in the `build()` method before building the target class. Having arguments in a builder constructor is both inconvenient and unhelpful. – Boris the Spider Oct 26 '14 at 11:12

1 Answers1

1

The short answer is "Usually not".

You should use final based on clear design and readability rather than for performance reasons.

Does use of final keyword in Java improve the performance?

Community
  • 1
  • 1
Andrés Oviedo
  • 1,388
  • 1
  • 13
  • 28