How to Code Like a Java Newbie
Last updated Wednesday, 27-Oct-1999 19:12:40 PDT by Roedy
Green ©1998-1999 Canadian Mind Products.
You might want to masquerade as someone young and inexperienced. Here
is how to do it in your Java Code.
Boolean Redundancy
Newbies love to balloon out their code with redundancy. Here are some typical
examples: Newbies will write:
An experienced programmer would handle that as:
A newbie might try:
It should be handled:
A newbie might code:
It should be handled:
avoid:
boolean b;
if (i <
7 )
else
just use:
Similarly avoid this redundancy:
just use:
String Redundancy
Newbies love to write things like:
String s =
new String(
"abc" );
To avoid littering the constant pool with redundant Strings, this should
be written:
Newbies write things like:
To avoid littering the constant pool with redundant copies of "", this
should be written:
If Redundancy
if (i <=
10)
else if (
11 <= i &&
i <= 15 )
should be written:
if (i <=
10)
else if (
i <= 15 )
Too Big And Flexible a Hammer
Newbies discover exceptions and use them where simpler and more efficient
constructs would work better. For example they might use them in place
of a loop ending condition or even a boolean return flag.
Reflection dazzles, and newbies will use it where simple interfaces
and delegate objects would suffice.
Sometimes an old-fashioned if or switch statement
is easier to understand and maintain than a complicated nest of inherited
classes. A newbie is intoxicated with the power of oo and wants to use
it everywhere.
The more advanced newbie might discover the facade design pattern, and
go overboard thinking that every class should implement every method with
a wrapper.
If you enjoyed this essay you might like this one on how
to write unmaintainable code.