Click here to Skip to main content
15,892,839 members
Articles / All Topics

Better Way to Comment... Code It

Rate me:
Please Sign up or sign in to vote.
4.33/5 (2 votes)
12 Oct 2010CPOL2 min read 7.3K   1   1
Better way to comment... code it

There’s been lot of discussion on the usefulness of comments in code. Many believe they're not required and are actually a smell that your code is not readable enough.

I'd agree with that philosophy and also feel if you must add comments, add it to explain ‘why’ of the code, not what the code does. Here I’d like to explain with an example how you can get rid of some of your comments in the code.

Let’s jump to code directly. Here’s the code that we'd clean up for this example.

[This code is for this example only. Other design decisions are not considered.]

Java
public String recommendGift(double budget){
	// get gifts from helper
	String[] gifts = giftHelper.getGifts();
	String gift = null;

	for (int i = 0; i < gifts.length; i++) {

		gift = gifts[i];

		// find out if gift already given
		boolean isAlreadyGiven = false;
		for (String given : giftsGiven) {
			if(gift.equals(given)){
				isAlreadyGiven = true;
				break;
			}
		}

		// calculate rating and budget
		int x = rating * 200;
		boolean ok = budget < x;

		// if both conditions satisfy, give it.
		if(!isAlreadyGiven && ok){
			giftsGiven.add(gift);
			// increment maintenance cost of the girlfriend
			maintenanceCost += budget;
			return gift;
		}
	}

	return gift;
}

The code is fairly straightforward. From a list of gifts, it selects the first gift that is not already given and is within the budget. There are few issues with it.

  1. The method is fairly long.
  2. It does too many things.
  3. It is not very readable... even with the comments.
  4. The comments tell you what the code does. That's the code’s job, isn’t it?

So let's try to clean this code. To start with...

This is fairly obvious and doesn’t need the comment. This kind of comment should be avoided. They does not promote readability. In fact, they have the opposite effect.

Java
// get gifts from helper
String[] gifts = giftHelper.getGifts();

Next up, let's move this code with the comment to a separate method. The name can be derived from the comment that is given above. It would turn from.

Java
// find out if gift already given
boolean isAlreadyGiven = false;
for (String given : giftsGiven) {
	if(gift.equals(given)){
		isAlreadyGiven = true;
		break;
	}
}

to:

Java
private boolean isGiftNotAlreadyGiven(String gift) {
        boolean isAlreadyGiven = true;
        for (String given : giftsGiven) {
            if(gift.equals(given)){
                isAlreadyGiven = false;
                break;
            }
        }
        return isAlreadyGiven;
    }

If we continue the same way... the final code will look like this:

Java
public String recommendGift(double budget){
    String recommendedGift = null;

    for (String gift : giftHelper.getGifts()) {
	recommendedGift = gift;

        if(isGiftNotAlreadyGiven(recommendedGift)
                            && isUnderBudget(budget)){
            updateMaintenanceCostAndGiftsGiven(budget,
                                                   recommendedGift);
		return recommendedGift;
	   }
    }
    return recommendedGift;
}

private void updateMaintenanceCostAndGiftsGiven(double budget, String gift) {
        giftsGiven.add(gift);
    // increment maintenance cost of the girlfriend
    maintenanceCost += budget;
}

private boolean isUnderBudget(double budget) {
    int x = rating * 200;
    boolean ok = budget < x;
    return ok;
}

private boolean isGiftNotAlreadyGiven(String gift) {
    boolean isAlreadyGiven = true;
    for (String given : giftsGiven) {
        if(gift.equals(given)){
            isAlreadyGiven = false;
            break;
        }
    }
    return isAlreadyGiven;
}

Few things to note here are:

  1. The method has been split into multiple methods with names clearly specifying what they do. This makes it more readable.
  2. The size of each method is hardly 4-5 lines which is fairly ideal.
  3. The comments are gone, but the purpose is met. The code documents itself.

I tried to explain the motivation here in Programming as Writing.

Please do share ways you’ve implemented them and made the code better.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 4 Pin
Herre Kuijpers12-Oct-10 21:43
Herre Kuijpers12-Oct-10 21:43 
yes I absolutely agree on splitting up such code blocks into smaller and reusable pieces.

although in some cases I do feel that each function should be commented with respect to the 'why' as you stated. e.g. clearly mention the business rule. specially the public methods.

e.g. the isGiftNotAlreadyGiven is tricky since the name contains a negate. if the function returns true, what does it mean?
Also it should comment that the rule is that a gift can only be given once and must be under budget

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.