Look at the following code:
class Person {
String name;
int age;
Person(Consumer<Person> consumer) {
consumer.accept(this);
}
}
As you can see, I'm using "consumer constructor", so I can create a person like this:
var person = new Person(p -> {
p.name = "John";
p.age = 30;
})
Seems like this approach is much better than builder pattern or all-arguments constructor.
4 years have passed since Java 8 was released but nobody uses consumer constructors (at least I haven't seen it before).
I do not understand why? Is this approach has some pitfalls or limitations?
I have found one, but I don't think it is critical:
class AdvancedPerson extends Person {
String surname;
AdvancedPerson(Consumer<AdvancedPerson> consumer) {
super(); // <-- what to pass?
consumer.accept(this);
}
}
Sure we can create a no-arguments constructor in Person
and just call it in AdvancedPerson
consumer constructor. But is this a solution?
So what do you think about it?
Is it safe to use consumer constructors?
Is this a substitute for builders and all-argument constructors? Why?
It's neither safe nor elegant from my point of view. There are several reasons against this approach: The worst thing about it is that it not only allows but also forces you to let the this reference escape while the object is not initialized yet. This has several severely bad implications:
See the second chapter of effective java for best practices concerning creating objects.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With