Sobes.tech
Junior — Middle

What are the differences between instantiating an object directly and using the Builder pattern to create it?

sobes.tech AI

Answer from AI

Object instantiation directly occurs through a constructor call, for example, new ClassName(). This is a simple and quick way to create an object when all necessary parameters are known and the object is not too complex.

The Builder pattern is used for creating complex objects with many parameters, especially if some are optional or have default values. Builder allows step-by-step configuration of the object, improving code readability and maintainability.

Differences:

  • Direct creation: fast, but can lead to long constructors with many parameters.
  • Builder: more flexible, improves readability, and simplifies creating objects with many optional parameters.

Example of Builder in Java:

public class User {
    private String name;
    private int age;
    private String address;

    private User(UserBuilder builder) {
        this.name = builder.name;
        this.age = builder.age;
        this.address = builder.address;
    }

    public static class UserBuilder {
        private String name;
        private int age;
        private String address;

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

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

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

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

// Usage:
User user = new User.UserBuilder()
                .setName("Ivan")
                .setAge(30)
                .build();
What are the differences between instantiating an… - sobes.tech