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.]

    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 straight forward. 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. Thats the code’s job isn’t it.

So Lets 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 don’t promote readability. Infact they have the opposite effect.

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

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

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

to


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:

    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..

Advertisements

7 thoughts on “Better way to comment.. code it.

  1. I have always preached for descriptive function and variable names, as they help make programs readable but in my field (Mathematics) the trend is to get it done, get it quick and use as many one-letter variables as possible. I learnt Lisp very soon after C (which is what our department programs in) and the style of long function names in it suited me better than calling a function “solve” (instead of solveQuadratic, for example). Thus this was a read that ‘tingled’ me 🙂 Thanks for it.

    Cheers,

    Ruben
    In my blog: 8 Reasons for Re-Inventing the Wheel as a Programmer

    1. Excellent article man ,simple, straightforward and concise.
      I like your writing skill.

      I always believe comments is very important and instead of commenting “What we are doing” , should comment “Why we are doing”.

      another good convention is adding JIRA no if you are putting code for maintainence reason.

      do check my blog tibco tutorial
      and suggest on how I can improve it.

      I also don’t see how to follow your blog , Please suggest.

  2. Hello, this is a really fascinating web blog and ive loved reading several of the articles and posts contained upon the site, sustain the great work and hope to read a lot more exciting articles in the time to come.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s