Examine Java objects build variants.
Telescopic constructor NutritionFacts.java example.
Pros:
- simple.
Cons:
- poor scalability.
JavaBeans NutritionFacts.java example.
Pros:
- simple;
- scales well.
Cons:
- too much boilerplate in usage;
- inconsistency and mutability are permitted.
Builder NutritionFacts.java example.
Pros:
- simple usage;
- built instances are immutable and consistent.
Cons:
- too much boilerplate in class definition.
Elegant builder NutritionFacts.java example.
Pros:
- class definition is shorter than in classic builder pattern.
Cons:
- builder methods change existing instance, so the same builder can't be reused;
- properties are non-final, so object is mutable, see Is this a safe publication of object?
IDEA InnerBuilder NutritionFacts.java example.
Pros:
- fields only have to be specified, all of the methods can be generated by IDEA.
Cons:
- you have to use IDEA plugin;
- all of the boilerplate resides in source control system still.
Google AutoValue NutritionFacts.java example.
Pros:
- much more less boilerplate;
- automatic equals(), hasCode() and toString() methods generation.
Cons:
- it's a code generation nevertheless, so it requires something like "mvn compile" before using
- builder support is experimental (you must use latest version from GitHub).
Project Lombok Builder NutritionFacts.java example.
Pros:
- shortest declaration.
Cons:
- it's an AST manipulation i.e. the real magic :)
- plugin for IDE is required.
POJO Builder NutritionFacts.java example.
Pros:
- can be used in conjunction with AutoValue or Lombok;
- is recommended by Umputun :)
Cons:
- can't generate getters and setters;
- it's a code generation nevertheless, so it requires something like "mvn compile" before using.
Immutables NutritionFacts.java example.
Pros:
- boilerplate is gone completely;
- automatic equals(), hasCode() and toString() methods generation;
- automatic withXXX() methods generation;
- uses Java 8 features (Optional etc.)
Cons:
- it's a code generation nevertheless, so it requires something like "mvn compile" before using.
- Использование паттерна Builder в случае, когда мы сталкиваемся с конструктором с многими параметрами
- Элегантный Builder на Java
- IntelliJ IDEA plugin which generates an inner builder class
- Google AutoValue, Immutable Value Objects in Java with Google AutoValue
- Project Lombok Builder
- POJO Builder
- Immutables.org, JSON serialization