Hi all,
our coding standards [1] include include a ban on break,
continue, and multiple return statements. These restrictions
originate from Dijkstra's rules for structured programming
[2], which ensure a linear program flow and help to keep long
procedures comprehensible.
Programming has changed since then and I think the code we
write today (object-oriented, short methods) does not really
benefit from these rules anymore. In fact, using breaks or
multiple returns often results in code that is clearer and
easier to read. For example, take the following method:
String
findFirstMatch( List<String> strings ) {
for( string : strings ) {
if( string.startsWith( "/" ) ) {
return string;
}
}
return null;
}
Following our conventions, we used to write it like this:
String
findFirstMatch( List<String> strings ) {
String result = null;
Iterator<String> iterator = strings.iterator();
while( iterator.hasNext() && result == null ) {
String string = iterator.next();
if( string.startsWith( "/" ) ) {
result = string;
}
}
return result;
}
The second version is not only longer, I think that the
extra code to avoid the return even obscures its mechanics.
It's easy to miss the "&& result == null" in the
while condition which actually makes the difference between
finding the first or the last match.
I think that clarity and readability should be the guiding
principle for writing code, especially for framework code
that is read much more often than it is written. So I have
broken with these rules, first as an experiment, but
meanwhile I'm convinced that they are not beneficial
anymore.
I'm not saying that breaks and multiple returns should be
generally preferred, but neither should they be generally
avoided. Some code is better written with a break and I
don't believe that avoiding these statements makes our code
clearer or safer.
I therefore propose to lift the ban on break, continue and
multiple return statements, and at the same time to
reinforce our commitment to writing short and concise
methods in an additional paragraph in our coding standards.
What do you think?
Regards,
Ralf