Skip to content

Instantly share code, notes, and snippets.

@3DRaven
Last active March 9, 2023 13:24
Show Gist options
  • Save 3DRaven/9a11ef9d0c42df6bf5603628327d88b3 to your computer and use it in GitHub Desktop.
Save 3DRaven/9a11ef9d0c42df6bf5603628327d88b3 to your computer and use it in GitHub Desktop.
Java Builder with compile time checking of full initialization (Strict Builder pattern)
public class Person {
private final String username;
private final int age;
Person(PersonBuilder personBuilder) {
this.username = personBuilder.username;
this.age = personBuilder.age;
}
public static PersonUsernameBuilder builder() {
return new PersonUsernameBuilder();
}
public static class PersonUsernameBuilder {
public PersonAgeBuilder username(String username) {
return new PersonAgeBuilder(username);
}
}
public static class PersonAgeBuilder {
public final String username;
PersonAgeBuilder(String username) {
this.username = username;
}
public PersonBuilder age(int age) {
return new PersonBuilder(username, age);
}
}
public static class PersonBuilder {
public final String username;
public final int age;
PersonBuilder(String username, int age) {
this.username = username;
this.age = age;
}
public Person build() {
return new Person(this);
}
}
}
/*
1. Any method has only access for reading for fields (except of changing inner collections).
2. Only full initialized Person can be build
3. Any step of initialization has only one initialization method.
Person.builder()
.username("Bob")
.age(10)
.build()
*/
@3DRaven
Copy link
Author

3DRaven commented Feb 6, 2023

I think it need for project lombok. Because this pattern variant has lot of sub-builders. Exactly for code generation.

@3DRaven
Copy link
Author

3DRaven commented Feb 7, 2023

Well, of course you can have some other variants of controlled partial initialization with this pattern. By creating another chains of sub-builders. Same as multiple constructors. But I can't recommend it. Better solution only one chain with nulls.

@norritt
Copy link

norritt commented Feb 7, 2023

Once I made something similar for retrofit
let me show you... (but it is bit dotnettish...)

@norritt
Copy link

norritt commented Feb 7, 2023

@3DRaven
Copy link
Author

3DRaven commented Feb 7, 2023

Yes, something similar. C#, but yes :) Pattern it is description for solution of typical problem. Main idea of this pattern it is compiler checked initialization without any additional checks.

@3DRaven
Copy link
Author

3DRaven commented Mar 9, 2023

Created issue in lombok project
projectlombok/lombok#3367

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment