5 ms·
Interesting. At work the other day I saw someone use a similar pattern in Java 8, where they had huge (think 250 fields) nested DAOs meant to construct JSON fo
by quelltext 6y ago
Interesting.
At work the other day I saw someone use a similar pattern in Java 8, where they had huge (think 250 fields) nested DAOs meant to construct JSON for some odd external API using a method called wiz, e.g. (not actual example):
new Payment().wiz(p -> {
p.amount = 100;
p.currency = Currency.AUD;
p.method = new Payment.Method().wiz(m -> {
m.type = Type.CARD;
m.reference = "2323232...";
}):
});
Of course, these are mutable (and didn't need to be immutable in the use case), so they could have just used:
new Payment() {{
amount = 100;
currency = Currency.AUD;
method = new Payment.Method() {{
type = Type.CARD;
reference = "2323232...";
}}:
}};
Note that this kind of initialization (double brace initialization) was frowned upon once upon a time but I'm not sure its criticism is valid anymore today. Something something don't pollute the class namespace and creating links to outer objects.
Aside from not necessarily linking to the outer class like double brace initialization, the lambda solution does have one advantage. It provide an easy way to construct an immutable variant. You "just" have to make a copy of the class with all fields final and .wiz() produces only the mutable versions.
People will probably say "just use builders" but I honestly don't think their boilerplate (for both writing and also using them) is worth it, i.e. it's not just as simple/easy as creating a mutable /immutable pair with exactly the same content, just different modifiers on fields.
Long story short, it's good that this with keyword addition is discussed, but I think before that it's important to allow simpler initial construction of records. AFAIK they don't offer a nice way to do so, just the nameless constructors based on argument order (with a max limit as well like any method).