Comments on a few stylistic issues I noticed these past days.
Ted talks about "cuddled
else’s" (what a cute name):
} else {
AKA, the "cuddled else". I never heard of a name for this before. I use
this style extensively when I’m programming in Java, but it and all the
close brackets use up a lot of whitespace.
This convention is recommended by Sun, but I usually prefer to
have the closing brace and the next instruction on separate lines. Nothing
religious or artistic about this preference, the reason is pragmatic:
easier copy and paste.
For example, suppose you need to move the catch block to a different place in
your source. Compare the copy/paste operation between the following two
formattings:
try {
// ...
} catch {
//...
}
and
try {
// ...
}
catch {
//...
}
Cameron posted the
following code snippet, that I would also write slightly
differently:
public Object[] toArray()
{
int cItems = size();
if (cItems == 0)
{
return EMPTY_ARRAY;
}
Object[] aoItem = new Object[cItems];
// ...
return aoItem;
}
I have two remarks about this code:
- I tend to avoid multiple returns in the same method. They make it
harder to follow the logic behind the flow and it’s also inconvenient to
break at the end of the method in order to introspect the returned value.
- I always store my returned values in a variable called "result" (one of
the few things I liked about Eiffel). This way, I can highlight this
variable and pinpoint immediately where it is assigned.
Therefore, I would rewrite Cameron’s code this way:
public Object[] toArray()
{
Object result = EMPTY_ARRAY;
int cItems = size();
if (cItems >= 0)
{
result = new Object[cItems];
// ...
}return result;
}
(Cameron, note that I respectfully respected your insane indentation scheme).