This is what I believe to be one of the best examples of how "naked blocks" can be useful: it is a class which represents the position of a class member in a source file, for the purpose of sorting junit tests to run in the order in which they appear in source files. (Adapted from original code found here: http://intellijava.blogspot.gr/2012/05/junit-and-java-7.html)
As you can see, the compareTo()
method has three comparisons to make, and the results of the first two need to be temporarily stored in a local. The local has no special meaning, it is just a 'difference' in both cases, but re-using the same local variable is a bad idea, and as a matter of fact on a decent IDE you can configure local variable reuse to cause a warning.
@SuppressWarnings( "ComparableImplementedButEqualsNotOverridden" )
private static class MemberPosition implements Comparable<MemberPosition>
{
final int derivationDepth;
final int lineNumber;
final int columnNumber;
MemberPosition( int derivationDepth, int lineNumber, int columnNumber )
{
this.derivationDepth = derivationDepth;
this.lineNumber = lineNumber;
this.columnNumber = columnNumber;
}
@Override
public int compareTo( MemberPosition o )
{
/* first, compare by derivation depth, so that all ancestor methods will be executed before all descendant methods. */
{
int d = Integer.compare( derivationDepth, o.derivationDepth );
if( d != 0 )
return d;
}
/* then, compare by line number, so that methods will be executed in the order in which they appear in the source file. */
{
int d = Integer.compare( lineNumber, o.lineNumber );
if( d != 0 )
return d;
}
/* finally, compare by column number. You know, just in case you have multiple test methods on the same line. Whatever. */
return Integer.compare( columnNumber, o.columnNumber );
}
}
So, in cases like this, naked blocks are always my preference. Note how in this particular case you cannot offload the work to a separate function, as Kilian Foth's answer suggests. But even in cases where you can in fact move the code to a separate function, I prefer a) keeping things in one place and b) not bloating my code with lots of functions. Definitely a good practice.
(Side note: one of the reasons why egyptian curly bracket style truly sucks is that it does not work with naked blocks.)