Last active
March 9, 2023 13:24
-
-
Save 3DRaven/9a11ef9d0c42df6bf5603628327d88b3 to your computer and use it in GitHub Desktop.
Java Builder with compile time checking of full initialization (Strict Builder pattern)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | |
*/ | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Created issue in lombok project
projectlombok/lombok#3367