mardi 1 juin 2021

Builder pattern without inner class

Lets say I have this builder pattern. I searched everywhere but couldn't find why would I need to use inner class if outer class has public consturctor.

public class User {

private final String firstName;
private final String surname;
private final int age;


public User(UserBuilder userBuilder) {
    this.firstName = userBuilder.firstName;
    this.surname = userBuilder.surname;
    this.age = userBuilder.age;
}



public static class UserBuilder {

    private final String firstName;
    private final String surname;
    private int age;

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

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


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

Here I could rewrite this code without using inner class as :

public class User {

private String firstName;
private String surname;
private int age;


public User(String firstName, String surname) {
 this.firstName = firstName;
 this.surname= surname;
}


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

}
}

When I read about builder pattern they say this pattern prevents big consturctor blocks. And they use inner with setters (with fluent pattern). I don't understand why we need to create inner class I could do the same thing it without using an inner class if my constructor is public. Here another example for more complex variables:

class NutritionFacts {
  private final int servingSize;
  private final int servings;
  private int calories;
  private int fat;
  private int sodium;
  private int carbohydrate;


    public NutritionFacts(int servingSize, int servings) {
        this.servingSize = servingSize;
        this.servings = servings;
    }
    public NutritionFacts calories(int val)
    { calories = val; return this; }
    public NutritionFacts fat(int val)
    { fat = val; return this; }
    public NutritionFacts sodium(int val)
    { sodium = val; return this; }
    public NutritionFacts carbohydrate(int val)
    { carbohydrate = val; return this; }
    
@Override
public String toString() {
    return "NutritionFacts{" +
            "servingSize=" + servingSize +
            ", servings=" + servings +
            ", calories=" + calories +
            ", fat=" + fat +
            ", sodium=" + sodium +
            ", carbohydrate=" + carbohydrate +
            '}';
}
}

Aucun commentaire:

Enregistrer un commentaire