Quantcast
Channel: "on software and stuff"» programming
Viewing all articles
Browse latest Browse all 10

Better way to comment.. code it.

$
0
0

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



Viewing all articles
Browse latest Browse all 10

Trending Articles