Map<K, V> map;
for (K key : map.keySet())
{
doSomethingWithKey(key);
doSomethingWithValue(map.get(key));
}
Map<K, V> map;
for (Map.Entry<K, V> entry : map.entrySet())
{
doSomethingWithKey(entry.getKey());
doSomethingWithValue(entry.getValue());
}
Object value = DEFAULT;
if (condition)
value = new Object();
Object value;
if (condition)
value = new Object();
else
value = DEFAULT;
Object value = DEFAULT;
try
{
value = new Object();
}
catch (Exception e) {}
Object value;
try
{
value = new Object();
}
catch (Exception e)
{
value = DEFAULT;
}
Object value = computeValue();
if (condition)
return computeSecondValue(null);
else
return computeSecondValue(value);
if (condition)
return computeSecondValue(null);
else
return computeSecondValue(computeValue());
Have a question about something in this article? You can receive help directly from the article author. Sign up for a free trial to get started.
Comments (5)
Commented:
The variable initialization, for me is a bit incomplete. Perhaps because these days I spend a lot of time trying to write immutable objects. So I'd prefer this pattern over any of those shown:
Object value = (condition) ? new Object() : DEFAULT ;
That's because it supports this version:
final Object value = (condition) ? new Object() : DEFAULT ;
which shows up a lot if you're trying to make your objects immutable (so they perform better in multi-threaded environments or in Java 8's functional language features).
But aside from that small point, very nice advice.
Doug
Author
Commented:Open in new window
Looks like the compiler is able to figure out that the final variable is only ever going to be assigned a single value.
Commented:
Open in new window
to access the variable too soon, you'd get the "may not have been initialized" error.
Still, not sure I'd prefer the more expanded pattern myself over the more definitive "it's only initialized once because there's only 1 assignment statement" but you make a good point that it's more of a preference than a requirement.
Doug
Commented:
Author
Commented: