Inherit or compose.. Hmm..

When designing your domain/classes, this is one decision that always results in conflicts within teams. Whether to inherit from a class or to compose that class. This is fairly subjective but here are few pointers for discussion..

Lets take this code for example:

public class GiftCollection extends HashSet {

    public Gift getRandomGift(){
        List giftList = new ArrayList(this);
        Collections.shuffle(giftList);
        return giftList.get(0);
    }
}

It is a collection of gifts that is represented as a set. The additional behavior from a set is that it can give you a random gift. It looks fairly straight-forward and would work in a even more straight-forward manner. Lets look at a usage of this..

public class GiftSelector {

    GiftCollection giftCollection;

    public GiftSelector(GiftCollection giftCollection) {
        this.giftCollection = giftCollection;
    }

    public Gift selectRandomGift(){
          return giftCollection.getRandomGift();
    }

}

This is a basic usage of the GiftCollection provided earlier. If one looks closely, though the two classes look very similar and doing similar things, there are basic differences between the two.

GiftCollection inherits a HashSet and extends to the behaviour by adding another method getRandomGift to it. However GiftSelector decided to contain a GiftCollection and delegate few calls to it.

I’ve always preferred the latter approach for following reasons:

1. The classes (both superclass and subclass) are much more flexible to change.

In this case, if GiftCollection decides to change the signature of the method getRandomGift(), it would not have an effect on the callers of GiftSelector, since it wraps the method call.

But any change to the Set implementation would affect the api of the GiftCollection class, without its knowledge. The users of GiftCollection have to change their code, though there has been no apparent change to the class. This is not an ideal scenario.

2. Easier to test.

It clearly shows that GiftSelector is much easier to test than GiftCollection. One can easily mock the dependency of the class and unit test the code. Whereas, in the case of inheritance, most mocking libraries do not provide a way to mock super classes. So its difficult to test in isolation.

3. Polymorphism through Interfaces is more flexible

One of the reasons for inheritance has been to reduce code and take advantage of polymorphic behaviour. Interfaces provide a more flexible way to achieve the same result. Composition coupled with Interfaces present a better alternative to achieve polymorphism.

This is not to say that one should not use Inheritance.

When modeling your domain, Inheritance should be used in case of a direct ‘is-a’ relationship. It should not be used only to achieve code-reuse or polymorphism.

Prefer composition over inheritance, unless you have good reasons to not do so..

Would love to hear your thoughts on this..

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

How to find yourself a good programming job

Tricky isn’t it.. especially when you’re a programmer.

Its not about just getting a job anymore, isn’t it. We all need a good job.. a good company to work with. Right set of people to work with. Good environment. Good technology, nice product to work on.. etc. etc. You know all those good things.

But the reality is there are loads of companies out there treating programmers as commodities. You’re put under a manager who comes right from a factory environment.. (actually even the factories are kinda better nowadays). And before you know it, programming is just yet another thing that you do at your job. Probably the least important one too.

Many folks are happy with it. If you are, you are requested to return back from here. Stuff below can lead you in different direction..

So if you’re stuck at such a place, what do you do? How do you make the switch to the kind of workplace that you like.. A place where you’ll be at your menacing best. Thrashing programmatic solutions one after another. Discussing all fantastic tech stuff. Breathing fresh air and coding stuff that you like.. How do you find the right place?

Job Portal (Hmm.. still many programmers are recruited this way)

Job portals are a great way to land yourself in yet another place you want to get out of. I really wonder if companies should even bother looking at them, unless they need posers and half-arsed programmer look-alike in their company.

I mean, look at the process of recruitment.. You enter your resume (one which says nothing about you..) into a site which catches keywords like java, c, etc.. and not your real traits. Then you talk to a recruitment guy, who knows nothing about programming or programmers, except that programmers are a bit odd looking and need to be taught manners.

Then there’s a fantastic interview process. You are made to sit for longer durations, where they check your endurance and frustration limits. This gives them a good idea if that person can bear the frustration that is to ensue once he’s joined the company.  And once the actual discussion starts, its not actually a discussion. Its a one-way street. Questions being fired one after another which has very less to do with actual work that one does.

Its a clear recipe for hiring average folks. One who works for money and has little to no passion for programming as such. One who’s likely to bring all wrong practices into your system. One who’ll never bring an innovative thought, even if his life depended on it.

So you ask what’s the alternative..

Go network with programmers..

Go where good programmers hang out. Talk to them. Know where they work.

Hang out at conferences. Find companies that do good work. Companies that project the right attitude.

Build your personal brand online

Identify a good open-source project that you could relate to and start contributing. Else, start a project of your own and get other contributors to contribute to it.

Get yourself on Twitter, Stackoverflow and earn good reputation in the community.

Earn good referrals.

Earn recommendations and referrals from respected folks in your community. Identify companies that you’d like to work with and earn your way towards meeting their standards of hiring.

These are of course not easy to achieve, but yeah.. are sure going to land you a job which is better than the one you’re currently in.

Try it out..

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.

Coding. Interview as a Service – Part 2.

[tweetmeme source=”snarayan” only_single=false]

This is a continuation of the Interview as a service series. You can visit the part 1 here, where I talk about some of the common shortcomings in recruitment process of IT organizations.

Well.. to jump directly onto the subject, Coding. How many organizations have coding as a standard practice in their regular interviewing process? To your surprise, not too many. It is absolutely mind-boggling to how one can recruit programmers without actually testing their programming skills.

Programmers are supposed to program. Code. In any language, but Code. That is a absolutely non-negotiable. Any concept, any theory, if it is not demonstrated through code.. it is not correct. It is not good enough if one talks well, is well dressed and knows few technical buzzwords/jargons floating around in the industry. We’ve seen such folks struggle to write even the simplest of programs. And for all the referral process fans here.. these folks have lot of friends like themselves. They will refer everyone. No doubt about it. So you end up having a fantastic team of programmers who can’t program. Not program even if their lives depended on it.

This decision has to be made by the organizations. Do you want such posers in your system? If your answer is we’re fine with it, you can stop reading further. This one is not for you.

Ok. If you’re still here, I believe you understand the importance of recruiting right programmers. One of the important exercises to be done immediately is add 1 or more coding exercise in your recruitment process. Start with a simple problem, one  that requires some of the programming constructs and ask them to write code for it. Not pseudo-code. Actual program. Make sure the problem contains atleast 2-4 constructs like conditional logic, looping, modularization, data structure, etc.. as one sees fit. An example could be, from a list of numbers give me all numbers that are divisible by 3. As simple as that.

Look at how quickly one gets to solve the problem. In my experience, good programmers would be solving this the minute you’ve finished your question. Speed is not necessarily a measure of quality but can be treated as an indicator.

This is fine if you need just programmers. How about requiring good programmers? Do you need them? Yes.. ok lets go about doing it then.

Present a problem that involves more programming constructs and add a bit of design into it. You’d like to see how one goes about arriving at a solution. What are the approaches he takes. What are the approaches he doesn’t take, and reasons why. It can be a really exciting experience when you carry this exercise with a real good programmer.

I’d suggest doing this on premise and actually going through the whole process of arriving at solution. Thats the best way to do it.

One of the other approach I’ve seen is sending the problem to the programmer and ask them to submit the code. After submission, on premise, discuss with them about their choices and practices.

If you go with this approach, I’d rather suggest submitting code katas, screencasts.. This would give a nice idea of how a programmer goes about doing his job. How comfortable is one with his editor. What shortcuts does he use to get the job done. What classes he comes up with, etc..

To summarize, to build a good or even decent software organization, you need to focus on the kind of programmers you let inside. Better the programmers, better the kind of services or products you provide.

My interactions at Devcamp chennai..

[tweetmeme source=”snarayan” only_single=false]

Wasn’t a regular saturday for sure..

Last week, on saturday, I was in NDTV office observing the shooting of a show on social media and its influence on the way we interact..  One of the arguments was that People have forgotten the art of social interactions. There are very less real-world communities.

Well, this saturday, this argument was totally written off. At Devcamp, we had 100+ programmers (creators of the virtual world) under one roof and discussing the thing that they love most. Technology.

This is not a recap of all the things that happened at devcamp. Its only restricted to my interactions there..

First mention to few people who I was meeting after a long time. Mr. Dorai Thodla(iMorph), Mr. Suresh Sambandham (orangescape) and Sriram Narayan(Thoughtworks). I admire each of them a lot and for different reasons. Was great to catch up with them and talk about various things..

Next, loved the self-organizing nature of the event. People were free to move around, talk to different people and discuss things the way they liked. Although, I felt the awareness level about Open Space Conferences was fairly low on the attendees. So at times it got a bit chaotic. But taking nothing away from the charm and enthusiasm, it was a nice show.

The presenters, I expected much more live code and variety of styles, which was missing. Most of the presentations were powerpoint stuff. Seriously.. in a devcamp you need to see more code. Editors, syntax, program, they were a little less. Guess, that will improve in the further sessions.

I had a presentation of my own along with Deepan, my colleague and friend, on “Code smells and Refactoring”. Got few techies interested and had a nice time discussing finer details of programming. (I had a full code session. No presentation.)

Next up was lightning talks/fishbowl sessions, which disappointingly had very little participation. So we thought, we’d change the style and invite people to talk based on topics we chose. It was an interesting little session, which really caught my imagination. Some really interesting topics discussed there.. Some of them are as follows:

1. Inspiration as a programmer.. Names starting from Larry Page to Joel Spolsky were mentioned as inspirations for being a programmer.

2. Products that we’ve appreciated.. Stackoverflow, Delicious, Winzip, Hibernate, Gmail, etc. were mentioned.

3. Products that’ll make future interesting.. Google Wave, HTML5 & CSS, Mobile apps, mobile/e-commerce. Here’s a post on it by Dorai.

Apart from these, there were couple of young Entrepreneurs (still in college), who are trying to change the world. Pretty neat stuff.

All in all, Devcamp was a step in the right direction. Though, there’s a long way to go still.

Check out few tweets here

Pairing – Why does it work?

[tweetmeme source=”snarayan” only_single=false]

Pair programming is an extreme programming (xp) practice that involved two programmers work together to finish off a task. They typically share the same workstation too.

Well.. the general perception of programming is, you have more programmers you get more stuff done. Now, it seems extremely inefficient to have two folks working on a single workstation. You’re working at 50% capacity in someways.

This is absolutely false.

When correctly used, pairing can be a great productivity boost, also helping in sustained growth in quality.  Let me share my perception on pairing since I’ve used it..

1. Sharing tool.

A team can have its senior folks pair with its junior folks on a regular basis and ensure that knowledge is shared in the best possible manner, at work (inspite of a theoretical session).  Even within a project, knowledge of different modules can be shared with all members of the team through pairing.

2. Dependency management.

By sharing and distributing knowledge with team members, you’re also reducing the dependency on individual programmers/members of the team. Hence reducing the risk of people moving out or overpricing folks.

3. Culture of equality. (No hero worship)

Since the knowledge and responsibilities are divided so evenly, you tend to have less heroics at work. Hence providing a very healthy culture of trust and respect within a team.

4. Reduce Developer Block time.

As developers, we often get into a state where we are blocked with a problem. Either we do not know a solution or we know a couple of them and are not clear which one to go for.. With a third eye always with you, this can be reduced to an extent. Two people thinking about a problem increases the chances of a better solution coming along, since both programmers can bounce ideas off each other.

5. Parallel Code Reviews.

With people working with each other, you are getting reviews done parallelly without hurting each other’s sentiments :). Typically Code reviews happen to be badly done. Most developers hate to accept review comments once they’re done with their code. But since its done while they’re coding, it works fine for both parties.

6. Development of good practices.

There are many habits and shortcuts that can’t be taught in isolation. Sharing small tricks and shortcuts become really easy with pairing. Also when you’re pairing with somebody good, it can really motivate you towards programming.

I’ll have to agree that I did not believe in these things before I started incorporating them in our daily exercise.

It works for me.