Thomas said:
I didn't like having to assign the reference to a variable. Perhaps
something like:
Map<String, String> map =
Maps.builder(new HashMap<String, String>())
...
I'm not clear on why you dislike the assignment ? In the version I posted (I'm
assuming you've seen my other post by now) there is one variable which is
assigned once, in your version there is one variable which is assigned once.
Perhaps it's because you are focussing on this being a use of the Builder
pattern, whereas I am only trying to create an adaptor to permit the use of the
chained-send idiom (a more general notion than the Builder pattern).
For instance, in my terms, a method coded like:
void addStuffTo(List<String> list)
{
super.addStuffTo(list);
Stuffer.stuffing(list)
.add("one")
.add("two")
.add("three");
}
would make perfect sense, although it is not an application of the Builder
pattern (as I understand the term).
HashMap<String, String> map =
new Builder<String, String, HashMap<String, String>>(
new HashMap<String, String>()
)
The great thing about Generics is how they make the code self-documenting...
;-)
public static final class Builder<K, V, I extends Map<K, V>> {
As a purely technical point, the fact that this is Builder pattern forces you
to add the
I extends Map<K, V>
parameter in order to retain the concrete type of the thing under construction.
In my version, since it is only an adaptor, there is no need for the third
parameter. Although I /could/ add a get() method, the return type could be no
more specific than Map<K, V>, rather than (say) HashMap<K, V>, since the
adaptor has no reason to care about the concrete type of the object it wraps.
It's a pity this method is not compilable, because of some restrictions
that I can't say I really understand.
public static Builder<K, V, I extends Map<K, V>> I builder(I map) {
return new Builder<K, V, I>(map);
}
Or is that disappearing into the land of the horrible?
It certainly makes my eyes water a bit ;-)
I don't understand why the compiler won't accept the I parameter either -- but
then I have pretty much given up on trying to see the logic in what the
compiler allows and what it doesn't. I have fallen back on Voodoo programming,
and just try stuff until something works :-(
BTW, returning to the previous point: Since my version doesn't carry the more
complicated information about the concrete type of the target, my equivalent of
that method is simpler and seems acceptable to the compiler.
-- chris