søndag den 10. juni 2007

Comments can be bad and clutter code

Oh my heart bleeds for I have been deceived by my foulishness.
What I usually tell people when I can't understand their code is:
"Write lots of comments"

Which would solve the problem at hand, but maybe the problem is not my lack of insight, I should be able to comprehend most code, shouldn't I?

So instead lets take an example of some code I might misunderstand, an rewrite it so I could. I don't understand this(code segment randomly picked from http://www.google.com/codesearch):
You can look through it, or just press 'Page Down', to skip to the point.. it's hilaroius, trust me ^^

public static void main(String[] args) {
final int NUM_MSGS;
Connection connection = null;

if ((args.length < 1) || (args.length > 2)) {
System.err.println(
"Program takes one or two arguments: "
+ " []");
System.exit(1);
}

String destType = args[0];
System.out.println("Destination type is " + destType);

if (!(destType.equals("queue") || destType.equals("topic"))) {
System.err.println("Argument must be \"queue\" or " + "\"topic\"");
System.exit(1);
}

if (args.length == 2) {
NUM_MSGS = (new Integer(args[1])).intValue();
} else {
NUM_MSGS = 1;
}

Destination dest = null;

try {
if (destType.equals("queue")) {
dest = (Destination) queue;
} else {
dest = (Destination) topic;
}
} catch (Exception e) {
System.err.println("Error setting destination: " + e.toString());
e.printStackTrace();
System.exit(1);
}

try {
connection = connectionFactory.createConnection();

Session session = connection.createSession(
false,
Session.AUTO_ACKNOWLEDGE);

MessageProducer producer = session.createProducer(dest);
TextMessage message = session.createTextMessage();

for (int i = 0; i < NUM_MSGS; i++) {
message.setText("This is message " + (i + 1));
System.out.println("Sending message: " + message.getText());
producer.send(message);
}

producer.send(session.createMessage());
} catch (JMSException e) {
System.err.println("Exception occurred: " + e.toString());
} finally {
if (connection != null) {
try {
connection.close();
} catch (JMSException e) {
}
}
}
}

- okay I'm dumb I know, I know. In this case, the code was actually substanially commented, I just left out the comments, because then I would have a case. I found that several lines of comment could be left out, just be refining the code a bit. So I put away the code in little neat sections, and then embraced a form of procedural glamour. I came up with this:

public static void main(String[] args) {
handleInputArguments(args);
connect();
}


Now I understand what it does.. hooray for me! And no time wasted for comments.

Spin-off'ed
Trailing through the Internet with the great firefox add-on StumbleUpon.. I actually stumbled upon something extremely interesting:

http://www.chrylers.com/top-ten-of-programming-advice-to-not-follow

It is nice to hear what seasoned programmers think of advice given to me by various colleagues.