Rene Wooller wrote:Hi All,
A lot of people are saying how they wouldn't do this. Would you mind listing a few alternatives?
Personally, if I wanted to expose this map as a public field, I would want to ensure that not only is the reference final, but the object itself is immutable. We don't want anyone calling put() or remove(0 on the map once it has been constructed. Traditionally this could be done like this:
Or this:
But nowadays I would prefer to use
Guava:
Rene Wooller wrote:All I can think of at the moment is a declarative approach, using a properties file or xml or somesuch, in which case, the benefit would be ease or change.
Yeah, something like that could certainly be useful. If you want to load key-value pairs from some other source, I would put that loading code inside the initializeMap() method. You can do whatever you want there. If it needs more careful
testing, it's easy to make the method package-private or some other access. The reason I often prefer a named method to a static initializer is that it's easier to test a named method.
Rene Wooller wrote:But this would a bit of hassle. I think the example given would be faster to code, and I personally don't find it hard to read at all.
Well, it's an unusual syntax that has just started to appear recently. A lot of people don't like it simply because they don't recognize it - or because they figure many other people will not recognize it. Which I think is a fair point. If I'm going to bring in something new that people might not be familiar with, I'd rather it be Guava, because that makes the code look much nicer and gives many other useful methods as well.