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

Productivity Tips for Programmers

This post is dedicated to programmers who believe that spending more time on the project (in the office) is directly proportional to productivity of the programmer. Okay, I’ll break a secret here. “IT’S NOT“. Obviously you need to be in front of a computer to type, but the similarity with programming just ends there. Okay. So what should programmers do with their time?

Utilize portion of your working time honing your skills and updating on getting more productive. Here are a few simple things you can do:

1. Write Unit tests for higher productivity. (if you’re not already)

This is pretty basic stuff. But there are so many programmers who don’t do that. Well.. you should. This not only improves your code quality, it improves your productivity too. You’re not only more confident of releasing and modifying your code, you save a lot of time in the process as well.

Imagine you writing a large web application, a small code change means, rebuilding the application,deploying it and checking the feature (probably hidden under 5 links). Imagine doing it time after time. Now replace this with testing only that small change. This is a fairly practical example and with practice you can really gain a lot of time by testing effectively.

2. Practice your programming.

This is a no-brainer too. Look at other professionals. Cricketers improve their skills with ‘net practice‘. Musicians practice their instrument. Singers with their ‘Riyaaz‘. Amazingly, most of the programmers don’t practice.You should.

Take up a book like Effective JavaDesign Patterns and practice few principles per day. Take a few problems from Project Euler and solve them with your favorite language.

Unlike your regular projects, where you have a deadline, practice programs need not be time limited. So take your time. Do things the right way. With this practice your productivity will improve a lot in your regular work. It’s obvious, isn’t it.

3. Use libraries and help improve them.

There are many programmers who are library averse. They’d rather code it themselves than using a library. The primary reasons are:

  • They don’t know the library.
  • The library does lot of other things they don’t need.
  • They feel more in control with their own code.

Think about this

  • A library has been well tested and covers more scenarios,saving you lot of time.
  • When you improve on the library, it can help a larger community. Improving your private code couldn’t possibly have that impact.
  • To top it all, other folks are working on improving that library too. That indirectly helps your code.

In short, use a library unless it is too unsuited or heavy for your requirement.

4. Read code and technical stuff

Reading code and modifying is as difficult if not more than writing it in first place. There’s lot of good code available for reading in the open-source world. Pick up your favorite library and open up its code and start reading. You may not comprehend all of it immediately.. but with practice, you’ll be able to identify different patterns used and can incorporate them in your code too.

Apart from code, also subscribe to few technical blogs from good software experts and keep yourself updated on the trends.

Well, there are many other things you can do to improve your skills and be more productive in your work. These top my list. Do share things you do..

We’re just getting started with touch apps..

Its yet another post on the touch based tools and apps, but I couldn’t resist. So here it goes..

We heard about the coffee table from gates (Microsoft) a few years back.. The idea was to change the way human machine interaction modes. In layman terms, move away from a mouse, keyboard based interaction to a more natural way of interaction.. (i.e.) through voice, body gestures, pen, touch, etc.

It got me thinking. What happens when people are presented with such technology. How would people react to that?

Well.. I haven’t heard about the coffee table much since. But recently we were presented with a more portable version of it by a gentleman named Steve Jobs. Apple presented iPad to the world. One of the better products that has greeted the market in the last decade and maybe even longer than that. The options of utilization are massive, limited by only one’s imagination.

Here’s a look at recent future with touch screens..

It presents expandable, transparent and easily connected touch based apps. Thats one of the direction they’d move.

Children and Education:

Other area of applicability are children and the whole education and learning space around them. Have you seen a kid with an iPad in hand? Have a look at these pictures and figure out the most natural interface in this:

Obviously the third one with iPad looks the most natural for kids. Kids learn a lot through touch and feedback. With right kind of apps, it can be very intuitive and can change the face of child learning.

Help with Autism:

This also opens up unlimited opportunities to enhance improvement in communication especially for kids with communication disorders. There have been many stories where this interface has helped families communicate better with their special kids.  Have a look at this amazing heart-warming video and see for yourself..

Rural reach:

Owing to its size and intuitive interface, its again a natural choice for apps/services that reach out of rural areas in different parts of the world with low literacy rates. I’m sure with mass production and subsidized rates from government, this can be made available to huge population and large number of people can benefit from this.

Industries like rural healthcare, micro-finance and different services and benefit from this too.. There has been a recent announcement from Indian HRD ministry to launch a 35$ tablet. It may not be a possibility currently but it shouldn’t be long before we reach that point technically..

Looking at the impact that mobile has created in the rural sections, this would be accepted instantly.

What are your interview questions?

Well.. What are they?

Let me try and guess..

1. How long have you been working in Java/.Net?

2. What is your current project?

3. What are your current interests?

4. Solve this puzzle for me..

5. My favourite.. Tell me about yourself.

Let me tell you one thing. You’re not only wasting your time, you’re wasting the time of the other person too.. All the information is already available one way or the other on the net. Go lookup.

And if you don’t find his information on the web… be sceptical. Start the interview asking why you did not find any information about him on the web.

Lets stop being so superficial in interviews. Especially for developers. Please.

Go deep. Get conceptual. Ask him to code. That is why you recruit him.

Some of my earlier posts of recruitment are Part1, Part2, Part3, Part4

Emails are just getting hotter!!

Just when you thought Emails are losing their feet and better tools are replacing them, comes a host of applications on top of common emails. You’d agree with me when I say, there’s no bigger database than emails and if that data is studied properly, would reveal a lot about the person starting from personal stuff to professional. His taste in music, movies, choice of friends, business interests, job interests.. name a thing. Its available in the mail account.

This is what I’ve come across lately..

1. Rapportive


Excellent tool. You typically have social applications asking for emails to import your friends. Reverse it now. That’s rapportive for you.

You need to hover over the email id of the person in gmail and you can see the social profile of the person in different applications like linkedin, twitter, myspace, etc. Many CRM tools have tried to do this, in the bracket of Social CRM. But this tool integrates seamlessly with your email and nothing better than that.

It makes good use of the otherwise useless ad area. Is very unobtrusive and intuitive at the same time.

2. Priority Inbox

Always wanted a tool that would show you only the most important messages to read. Typically, you do it through labels and multiple inbox.. but nothing better than the email client filtering it for you. I’ve been extremely impressed with the simplicity of the feature, though not a very simple feature if you come to think of it. Certainly a move in the right direction.

Two excellent tools here.. and there are many more out there to make your email experience better.

Who do you have in your team?

[tweetmeme source=”snarayan” only_single=false]

Every now and then you come across a colleague who fits right into a stereotype. Let me try describing a few of them here..

The yes guy.

The guy never has a problem with anything. He’s at peace with everything in life.  There’s not a single negative bone in the guy.

Delivery is not assured though. Sometimes you wonder, does he really think before answering at all..

The no guy.

He’s an exact opposite of our “Yes Guy”. He almost always comes with a negative answer to a situation. Sometimes he himself doesn’t know why he’s objecting to a solution, but he objects nevertheless.

The reasons could range from wanting to be heard to absolute clueless. But he has to object.

The invisible guy.

The guy who’s never really around. He works at inhuman times. Doesn’t believe in discussing to bring about solutions.

Only reason he’s not fired is because he has a proven track-record of solving complex problems.

The innovator

The guy who pops up new ideas left, right and center. Anything conventional is just boring. He jumps around at anything new. Lets do the new library by that community, Lets move to the new version of the api.. Left to him, he’d be redesigning the solution every month with one of his new tools.

The problem guy.

“I once used this library and faced many issues.. I don’t seem to remember. But, it doesn’t work”. This is a typical statement from our Problem guy. He’s done it all and exposed them all. He knows problems in anything and everything that we use. Very handy at times, but really annoying otherwise.

The social guy.

The guy who can’t think beyond 140 chars. Always looking for things that he can put on his profile. For him, this is the augmented reality which he uses to build his social profile. You’d see him most of the times on his twitter or facebook account. Has more conversations there than within the team.

The lawyer.

The person who can debate on everything. He loves to talk. Loves to challenge the decisions. He doesn’t necessarily believe in his argument, but still goes about for the sake of it.

For him, the debate is more important than the solution itself. He thrives in discussions..

The Buzzword guy

Lets write a mobile app in functional language with a light-weight nosql db and deploy its data on the cloud”. Statements full of buzzwords are a signature of such people. He thrives on latest. Reads up any blogpost and tweet posted lately. Always upto date and keeps looking at newer buzzwords. Can’t construct a sentence without them.

We all play one of these roles interchangeably.. But frankly, this diversity is what a team is all about. If all were the same, it’d be pretty mundane

Programming as Writing.

[tweetmeme source=”snarayan” only_single=false]

I would completely agree with Eric Lippert when he says code is way easier to write than it is to read.

In Programming, as in writing, we present text and data. Data without structure is useless. How do I find things? How do I consume information? What is important and what is trivial?

When you read something, you expect a certain structure that saves your time and effort.. in absence of which you quickly give up. Lets look at few things that affect writing and programming in the same way.

Important information goes first

Table of contents, indexes and overviews should come first. They present a bigger picture to the reader. They help the reader to navigate through the content in a very smooth manner. Then comes the titles and then the paragraphs.

In programming overview is typically represented by package structure, and tiers. It isn’t as easy as it seems. It is extremely important to confirm to a structure and stick to it consistently throughout the content.

The titles, which would be method and class names, have to define what the following content is going to be. Well written title gets noticed and communicates the intent of the paragraph to the reader.

Then the paragraphs. It is extremely essential to break your content into many paragraphs. A carefully structured and organized content goes a long way in capturing the reader’s attention compared to a single large piece of content. So its important to break our in to proper classes and methods and keep them small and contextual.

Combination of small and well crafted classes and methods with well positioned names for them is a perfect recipe for fantastic prose.

Structure of information

You can structure your information is number of formats that can appeal to the reader. If you understand your readers well and can prioritize the important parts of your information, its wonderful. You can structure your information in the order of importance.

There are many layouts like Hierarchical, Linear, Non-linear, etc. Here’s a good example of a typical structure of a program.

Search-ability

You can provide extreme help to your readers if you make your content easily searchable. That means, readers can reach the content that they’re interested in, very easily.

Especially in softwares, since readers do not go through every piece of code line-by-line, it makes lot of sense to produce content that is very easy to search. Few things that can be done are:

Maintain the same vocabulary throughout the project. So when you name a variable as ‘salesTax’ at one place, it’d help a lot if you use the same variable name at other places in the code too. Making context specific searches extremely easy.

Name your classes and variables in terms of domain related terms. So instead of  a class named ‘SingletonFactory’ it’d be nice to have a name as ‘AccountManager’ or something closer to the domain.

Keep the content and the titles in the same context. So if a method says ‘calculateTax’ it should do only that. Other side-effects like auditing, interests should not be part of the method. They can be placed in their own methods or classes.

Getting a second opinion

Its easy to get lost in your own world and miss out many details. So periodically, one should review their content with few other readers. This would help you validate your assumptions and provide valuable feedback to improve on your writing. You can start out by giving an overview of the content that you’ve written and then let the reader find their way out through it. Observe them as they’re going through your content and how they’re navigating through the different structures.

In software programming, the process is called code reviews. This is where other programmers have a look at your code and provide their feedback. It is extremely important that you do that more often in your whole effort.

Read others

Its amazing to see how related reading and writing are. Once you start reading other people’s content, it has an effect on your own writing style. You tend to appreciate and adapt other people’s style and presentation of content. When you write you try to accommodate those learnings yourself.

You can setup reading groups to improve on your skills. Doing it as a community is extremely effective as you can discuss your views and assumptions with other people in the group and form a very objective opinion.

For programming, there is so much good code out there to be consumed. Start off with your favorite open source code and try to identify the patterns and styles that are used in that code. Try implementing those in your code as well..

Conclusion

In the end, its extremely important that you write. There’s nothing like writing. The whole process of writing improves your process of thinking too. Once you start thinking clearly, the same would show in your code. I believe writing (as in prose..) can have a very positive influence on your skills as a programmer.

So.. lets write. Lots of it.