Weight Loss Journey – A Better Analogy

There are times, when We The Software People keep aside the HTTP header and body and take a look at our own Header and Body. We don’t like what we see and we go, “Yikes, its Status 413: Payload too large.

This blog is about one such time.

At the start of this year, I had one such Status 413 moment and decided to do something about it. I joined a health club and lost about 12 kgs over a period of 4 months. It was a whole new experience for me. I don’t want to get into those details. They aren’t as inspiring or as interesting as this famous transformational video

However there’s one thing I have realized during this journey

The PROCESS to lose weight is extremely simple.
But FOLLOWING the process is extremely difficult.

Being a great fan of analogies I was looking out for analogies that show this difficult journey. The one that kept popping up everywhere on the internet was the 80/20 rule – “Weight loss is 80% diet, 20% exercise” with the following pie chart image.

 

wt-loss-formula

The 80-20 Rule

 

 

In theory this is correct, but I felt the representation is completely wrong. If you look at the pie chart image, you would think that diet and exercise are completely unrelated and independent of each other. It gives you a feeling that you can  A> Completely ignore the diet. B> Just concentrate on exercise and still get a 20% benefit !!. After all it’s so much easy to go on a walk in the morning than drink green tea every day.

This one big misunderstanding is quite prevalent. Everyone who wants to lose weight start off their weight loss resolution as – “I will start walking everyday from tomorrow” or “I will join a gym from tomorrow”. And we all have seen what happens to these resolutions. Long time back, I too had made this assumption and joined a gym. Never did I look at my diet. After a month of exercise I decided to quit. The weighing scale had not shown any change and I didn’t see any benefit in sweating it out.

My point is that the famous pie chart image puts you off. A picture is worth a thousand words – a lot of them unsaid. Sometimes those very unsaid words lead people to make the wrong assumptions. If we have been recommended 1 hour of exercise and rigorous diet, we think doing half an hour of exercise and dieting 3 days a week will still give us 50% benefit. Unfortunately it doesn’t work that way.

To better explain how the process works, I have come up with another analogy. One which I feel is better in conveying the idea visually.

Imagine you have to go from a base of a mountain to the plateau. The slope is steep, but the plateau is flat. That slope is your weight loss journey. You cannot stop on the slope. You have to continue walking till you reach the plateau. Otherwise you will fall down. The plateau represents a steady state once you have achieved your goal.

 

wt-loss-journey

Rather than the 80/20, I would divide the slope into 50% of Dedication, 40% of Nutrition and 10% of Exercise

These three – Dedication, Nutrition and Exercise are not independent. Instead these are linked together as if in a chain. Having Dedication is a pre-requisite of Nutrition. And following good Nutrition is a pre-requisite of Exercise. If you do exercise without Nutrition or just plan on Nutrition and Exercise without putting any dedication, you will fall off and return to Ground zero of the Base. Each of these HAS TO “Happen-Before” the next one to be really successful.

The first 50% of the slope represents your own determination, your own willpower. That’s the biggest challenge you will face in your journey. Unless you decide to do it, nothing will work. Nor can anyone help you at this point. You can appoint the greatest trainer or dietician, but they won’t be able to help you unless you yourselves firmly “Decide”. You need to understand and accept that getting fit (rather than just weight loss) requires a lifestyle change. You cannot continue your current lifestyle and expect a miraculous weight loss.

Insanity is doing the same thing over and over again and expecting different results.

– Einstein

When it comes to weight loss, I think we all are guilty of insanity. Everyone wants to be fit. but no one wants to change. I have wanted to lose weight for the past few years. Yet I didn’t do anything different and still expected to lose weight. So the first step of this journey is to get rid of this insanity and dedicate yourselves to a lifestyle change. Do this and you have crossed 50% of the journey. Ignore this and you are bound to remain where you are.

Once you have really “DECIDED”, the next 40% of your journey would be your diet or nutrition. You need to take a long and hard look at what you eat versus what you should be eating. This is the second big challenge you will face. Its not easy to give up those bad habits that you may have developed over a long period of time. The only consolation I can offer for this stage is that once you actually give up your habits, you would realize that it wasn’t as bad as you had thought it would be. I was shocked when I was asked to give up my daily few cups of tea. (Those who know me would know that my definition of “few” is around 6 cups). And yet after I actually stopped, it wasn’t that difficult.

Once you are dedicated and have altered your diet, you have already reached 90% of your journey. However a great danger lurks at this point. Remember, even though you have climbed 90% , you are most vulnerable at this point. Falling after climbing 10% is a small disappointment. Falling after 90% is disastrous. The only way out is to start exercising. It’s not optional. You HAVE TO. No matter how much dedication you have and how strictly you control diet, it cannot be for lifetime. There will be a time when you would want to eat that Ice cream Sundae or Vada Paav or maybe just go to Barbeque Nation and hog those delicious starters. It is very very difficult to control your impulse for a long time. No one, I repeat, No One can be on a prolonged calorie deficit diet. The only help you have at that point is to burn those extra calories through exercise. Exercising also helps you gain Muscle Mass which increases your metabolic rate. Once you develop your lean muscle mass, you would be burning more calories even while sleeping. As the financial experts say – Don’t work for Money, Make your money work for you. In the same way, let lean muscles burn calories for you.

Now that you have dedication, have control on your diet and do regular exercise, you are unstoppable. You would start seeing a steady weight loss as well as improved fitness. Soon you would reach the plateau of a fit body. Once you reach this level, you are on safe ground. You don’t really have to put in extra efforts to maintain your weight.

The only thing you have to do at that point is to NOT LOOK BACK. Just keep moving forward. Of course you can still fall down if you start moving backward by giving up all the exercising and good eating habits. But after such a long and difficult journey, I am pretty sure you would have started liking the “New You”. Giving up good habits at this stage becomes difficult and Dedication comes easily. Moving forward then comes across easily like a normal habit. In software terms it then stops being a development project and moves into routine maintenance stage.

Well, I started out thinking this would be a small blog but it has become quite long. So let me stop myself now and lend you my ear.

Have you had any similar experience? Do you agree with this analogy? Do you have an even better one to share? Let me know in the comments below.

Advertisements

End Of An Era

Me: What do you mean deprecated?
My colleague: The support will be removed from next version.
Me: I know that, but This?. It can’t be deprecated. You must be kidding me, right?
My colleague: No, look here.

And I looked. And looked. Rubbed my eyes and looked. It was true. Never in my wildest imagination had I thought I would see this day.

Postfix and prefix operators (i++, ++i) were being deprecated in Swift 2.X with plans to remove it in 3.0

For a person like me who started programming with C, this was sacrilege. It was like suddenly someone announcing there would be no vowels in English language. Or that kids will no longer be taught Jack and Jill.

i++ is THAT Fundamental to a C programmer.

After the initial shock wore off, I did some Googling and reached the proposal for removal of the postfix and prefix operators – https://github.com/apple/swift-evolution/blob/master/proposals/0004-remove-pre-post-inc-decrement.md

And a strange thing happened. When I read it, I actually found myself agreeing with it. In my earlier post here, I had myself berated the stupidity of doing things like these

j = i++ + --i + i ;

Other than ‘Showing off’ by the original programmer and ‘Pissing off’ the eventual maintainer, such statements do nothing.

The other argument against i++ was that for loops have evolved over time. Which is again true. Not just in iOS but in Java too. I searched my current java code base and found that I have been using i++ only in C style for loops like these

for(int i=0; i < N; i++) { 

    //do something here 

}

Even here it was more of my comfort zone with this type of for loop, than any special preference for i++. Java 8 had introduced streams and lambdas with the promise that imperative loops would be history. But the imperative loops were still there. All over the code. And because of one thing only – My Inertia.

So I thought why not try to see if I can remove all of these. Just assume that Java too deprecated i++. How would I change these?

Surprisingly it was easy. Yes, I had to get into the details of Java Streams and Lambda functions. That was a time consuming process and there was a learning curve there. But once I crossed the curve, it started feeling natural. It was more like – “Why didn’t I use this earlier?”

The following code becomes so self explanatory than a corresponding for loop

getServices().stream()
  .filter(s -> s.status() != DELETED)
  .map(s -> s.getBookingAmount())
  .reduce(BigDecimal.ZERO.setScale(2), BigDecimal::add);

And no, its not because it reduces the lines of code. The “Line of Code” is a stupid metric that I may rant about later. It’s more because it is such an elegant and imperative way of processing Lists.

SQL did it to databases ages ago. No one writes code to loop over records and Sum the result. No one writes code to join two tables in a database based on a primary key and foreign key. Why do we still do it in Java?

Anyway I digress.

Coming back to my original topic, it’s now official. i++ has now become a relic from the past. It had its glorious days, but its time that we move on.

An Era Is Coming To An End.

The Test Drive

[Note: I am using ‘he’, ‘his’ etc throughout the post. Just assume I mean ‘he/she’ when I say ‘he’ and ‘his/her’ when I say ‘his’. I am way too lazy to type it that way every time.]

It’s easy to check if a candidate you are interviewing is good technically. Ask him a few questions, get him to write some code and you can figure out his technical level. However it’s not that simple when it comes to determining how he would behave. How do you determine his traits? Is the person ambitious, is he a team player? You can’t ask him point blank. He would of course say what you want to hear. Have you ever seen a person saying that he is “NOT” a Team player?
But now, this difficulty is a thing of the past, for I have found the perfect and infallible way to test the candidate’s behaviour.
[Drum rolls in the background]

The way to do it is to take him out to a Test Drive. Yes, you heard it right. Just take the candidate out to a long winding drive through the city and observe his driving.

Why do you want to ask questions like How well do you drive the project? Are you driven? and hope for an honest answer. You can relax and actually observe the same while the candidate drives.

Here’s my quick start guide on various behavioural classifications based on the Test Drive

  1. The Automatic Gear Guy – He wants only an Auto Gear car. Frowns at a Manual Shift. He is willing to invest upfront in the right tools so that his life becomes easy. Prefers an expensive option in order to drive in comfort. He will spend time and energy selecting the right tools. Most likely he would be a little lazy. But do realise that lazy people can be great innovators. After all an active, health conscious guy wouldn’t have invented the TV Remote.
  2. Sir-Honks-A-Lot – The name says it all. Keeps honking and shouting at pedestrians as well as other cars. Will always blame others for any problems. Never looks inwards. Pleads helplessness. As he sees it, the problem is always because of someone else. This guy is a great person to have on your team if you are in a multi-team project that is missing deadlines. He would keep complaining about others loudly making your team appear like a poor lamb stuck with wolves. Kind of like Arvind.
  3. Formula One Racer – He has to be at the forefront. overtakes every other car. Doesn’t allow anyone to pass him. Wants to be Numero Uno – and stay there. Highly Ambitious as well as jealous. Not a Team Player, but could be a good catalyst to push your team to the limits.
  4. Leftmost Laner – The perfect foil to the Racer. He is happy and content driving in the leftmost lane (the slowest lane). He is not bothered if others go ahead of him or are behind him. He drives at his own pace enjoying the journey. He is the Tortoise to the Formula One Racer’s Hare. Slow and Steady. If you are looking at investing for long term, bet on him. Even better have both Leftmost Laner and Formula One Racer in your team. It will be like Yin and Yang – balancing one another.
  5. Whose Lane is it Anyway? – Doesn’t believe in lanes or driving within a lane. He owns the road and he has the right of the way. Pull, Push, Reckless Merge is his Mantra. Code Conflict, what’s that? Resolve using ‘mine’. Doesn’t matter if it overwrites 10 other changes and 3 days of dev effort is lost. If you hire him, make sure you have well-oiled Continuos Integration processes in place and heavy fines for breaking the build. Otherwise you would be spending a lot of energy fixing his mess.
  6. The Star Trek Guy – He boldly goes where no one has gone before. He can drive a car to the left of the leftmost lane or to the right of the rightmost lane, which you wouldn’t have thought physically possible. Can find paths where none exist. Can hack into an open source framework and make tweaks needed by your project. A great guy to get you out of any Jam. A must have for every team.
  7. The GoT guy – Utterly unpredictable. He would be in the leftmost lane at a red traffic light. When the light turns green, he would abruptly turn right. [Side Note: All the autos in Pune fall in this category]. Extremely unreliable. Just when you think he has found true love in Java, he would declare that Java is dead and start adoring Ruby. One day he wants to be a Tech lead, the next day he cribs that he is not getting enough management responsibilities. Avoid him.
  8. Can’t drive/Won’t drive – Yes this category actually exists in this day and age. I have come across the following reasons for this –
    1. Born and brought up in Mumbai. Relies on public transport and/or company transport
    2. Has driven in a foreign country and scared to drive in India
    3. All of the above. [Yours truly falls under this :)].

Then there are exceptions like THIS GUY who take the phrase Don’t drink and Drive literally – they don’t drink and they don’t drive. Anyway I digress. If you come across a candidate who can’t drive or won’t drive, there is a nifty trick that you can use to judge their behaviour.

Eager to know the trick? Pre-order my book – The Test Drive – slated for a September 31st release.

Ground Rules

Going through my backup mails, I found these interesting rules I had set. 5 years back, I was onsite at client location and these were the ‘ground rules’ I had set up for my offshore team at the start of a project.

I think they are still relevant.

  • No weekend work. No late nights. Not even late evenings.
    • Work smart, not hard.
    • The end result counts, not the hours that you put in.
    • Late work is just an illusion of being more productive. Don’t fall for it.
  • EOD for any deliverable/commits = 7 PM.
    • Anything delivered/committed after 7 PM will be considered next day’s deliverables and responded accordingly.
    • Leave office when you are done. It does not matter how long your superior stays in office.
  • Do not slog because of wrong estimates.
    • If you believe the estimates are wrong and it is impossible to do it in allotted time, let me know. We will together work on correcting it.
  • The above rules apply to Onsite too
    • Do not call call me after 10 PM MST (10:30 am IST) or on weekends 🙂
  • There will always be exceptions
    • There will always be exceptions to the above rules. Let’s keep them as exceptions and prevent them from becoming rules.

Quote

The Indian IT Crash of 2025

An IT Crash is coming. And its not going to be pretty.

I am not being pessimistic here. I just think that there are various trends that, when combined, would ultimately lead to a crash. I believe a perfect storm is brewing.

No room at the top

When I joined the IT industry 13 years ago, a 2 year experienced guy would be considered a senior – most likely onsite returned. A 4 year experienced person would be managing a project, while a 10 year experienced person would be heading a client account. A 15 year experienced person was pretty rare and considered close to God.

This has changed a lot in past 10 years. A person may not go onsite even after 5 years of experience, may not become a project manager after 10 years and pretty rare for him to head a client account even after 15 years of experience.

And hey – no one is retiring!!! In any mature industry, there are retirements and fresh hirings maintaining the balance. IT industry is currently only hiring. No retirements. Well almost no one.

There is simply not enough room at the top to accommodate everyone.

Rise to the level of incompetence

Every person rises to his or her level of incompetence. In the Indian IT context the push has rarely been technological development. It has always been managing others. Especially the big service companies had to push people to grow quickly. And by “growth” it always meant “Manage more people”. Look at any service company. There is a well defined career track for managers. But not for technology focussed individuals. This prompted people (who were good developers) to switch to project management. Unfortunately a good developer has not translated into a good manager. The skills required are completely different.

This has resulted in a lot of people rising to their level of incompetence. With hardly any room at the top, they are stagnating.

Newer methodologies like Scrum completely do away with managers for the day to day executions. Instead of a dedicated project manager, the focus is on a self-organised team.

We have already got a peek into what companies might do with mid-level managers that they feel are not performing.

With great salaries come great responsibilities

Today, I earn almost ten times of what I used to earn as a fresher. Even considering the inflation, this is way more than what any other industry pay hikes are. Even the same IT industry in US does not have such huge increments. Currently an entry level developer gets 3-4 Lakhs on joining, 5 years experienced gets 10L, 15 years wants 25L and after 25 years he probably demands 35-40L.

(Disclaimer: I am not into HR or recruitment, so these numbers may be completely wrong. Believe them at your own risk. Don’t sue me.)

Currently, companies are paying these  salaries as the demand is more than supply. But what happens when the supply increases – as it will – in the next 10 years? Does a 25 year experienced person really give an output of 10 freshers? Can he give an output five times of a 5 year experienced person?

On the other hand the client billing has not increased. The client keeps paying the same amount in dollar terms, while the salary of the developer is increasing. Every Indian IT company keeps talking of margin pressures in their quarterly results.

The current salaries are simply not sustainable.

When the cash runs out, guess who will be the first one on the block?

Frameworks, Automation and Cloud

The IT industry is fast maturing. Newer and newer frameworks keep simplifying the repeatable and mundane tasks needed. For e.g. the following Spring Data code creates all necessary CRUD operations plus adds a findByCode method.

public interface CategoryRepository extends MongoRepository<Category, String> {

    public Category findByCode(String code);

}

All this without writing a single SQL query. The same would have needed a whole day for a software developer 10 years back. With this framework that developer is no longer needed.

The automation space has exploded. Once configured, each commit can trigger build, test and deploy – right up to push to ProdWhere a company would early need a dedicated team  to build and deploy, the same can now be done with a click of button by the dev team itself.

Cloud has revolutionised the infrastructure management. I have absolutely no experience in infrastructure management or hardware provisioning. But I can now commission and decommission servers on AWS with just a few clicks.

These are exciting times. But it comes at a cost. Everyone is investing in automation. No one’s talking about hiring people.

Highly Leveraged

 

A majority of Indian Software developers, especially at my age, are heavily into debt. It could be in the form of a Home Loan, a Car Loan, a Personal loan or all of the above. EMI constitutes a majority of the monthly expense. In my discussion with them, I have realised that losing a job would be devastating for them. There are very few who said they may be able to sustain for 6 months without a job. A layoff would cause them to take another job quickly – even with reduced salaries.

Though this won’t be a factor for the crash, this would result in a domino effect.

Increased Dev Supply would result in Layoff – which would result in people ready to work for lower salaries – which in turn would result in more supply –  resulting in more Layoffs and so on.

Conclusion

 

I don’t know when the crash may happen. It may be ten years away or it might be next year.

But Winter is definitely Coming. Are we prepared for it?

 

 

What’s the story you want to tell?

Numbers don’t lie.

No they don’t.

But that doesn’t mean that they have to tell you the complete truth. Numbers can be coaxed into telling a partial truth. After all numbers don’t speak themselves, “someone” quotes them as part of a “Story”. And that “someone” has the power to decide any “Story” he wants to tell and then pick and choose the data. A story is first decided, data is then manipulated to fit the story. Instead of “manipulated” you can call it ‘coaxed’, ‘massaged’ – any term that makes you feel least guilty.

Oh how I miss the wisdom of Sherlock Holmes

It is a capital mistake to theorize before one has data. Insensibly one begins to twist facts to suit theories, instead of theories to suit facts

Just look around you. Based on “hard facts” Colgate is the #1 toothpaste in the world. And apparently, also based on “hard facts” Pepsodent is #1 toothpaste in the world. No one is lying, everyone is just giving you partial data that suits them. Similarly all news channels are the Most Watched News channels. What they probably leave out is the category under which they are deemed “Most Watched” – some are probably Most Watched in the category of “5 to 10 years age group who love nonsensical shouting and quarrelling”, but that’s not disclosed. That would hurt the “Story”.

This “Story Telling” is not just in marketing, it is rampant in software industry too. If appraisals are conducted based on some hard numbers like code coverage, defects injected, defects detected, defects fixed etc, developers soon figure out a way to manipulate those in order to provide a “Feel Good Story” about themselves.

Managers even go one step further. They can use the same facts and still spin it into a whole different story. I have seen a project that was perennially on fire. Developers were working 12 hours per day, even over weekends. I happened to see the final project closure report. It mentioned – with corresponding hard numbers of course – an effort overrun of just 5% !!!!. 50% extra every day + extra weekends equals 5% ?? That’s the power of Story telling.

Recently I heard an investment consultant talking eloquently about equities and how they are much superior than traditional fixed deposits. I have always been amazed at how they can convince people about the power of equity, no matter what the state of market is. If the market is up, they say look it is up. If it is down. they say equities are long term investment, it will always outperform traditional deposits. One thing I have noticed is they never define the term “Long term”. Is it 3 years? Is it 5, 7 or 10? That detail is left ambiguous. This gives them flexibility to come up with any data numbers they want based on the time period that is most convenient

So I thought why don’t I dig up some data and come up with few stories of my own. I took Infosys share price over the past 10 years. Infosys was chosen as it is a darling stock for all the investment story tellers. I am sure everyone must have heard at least one story that goes something like this – “If you had invested 10,000 in Infosys in 1993, you would have been a multi millionaire by now”. Unfortunately the Infosys website has only past 10 years of share data, so that’s all I had to play with. Couldn’t really come up with a rags to riches story starting from 1993. I also had to adjust the price of the shares as Infosys has time and again announced a 1:1 bonus.

I then came up with 2 main stories – Equities Suck & Equities Rock. And then I wanted to tell these stories over different time periods. Equities Suck over 3 years, Equities Rock over 7 years. Equities Suck even after 9 years and so on.

And guess what – I could build all possible stories from the underlying data.

Yes, each and every one of them!! I just needed to choose an appropriate start date and end date. And Lo and Behold – I had a story.

I have published all the stories in Story Board Format using Tableau Public – What Story Do You Want To Tell

In each of them, green line indicates a traditional fixed deposit performance, while the orange line indicates Infosys Share performance.

The last one shows how the returns have oscillated over multiple year time windows. That will give an idea of what dates to pick if you have a particular story in your mind.

So what are you waiting for? Go ahead, pick one or create your own.

What’s the story you want to tell today?

 

 

 

 

 

 

 

 

 

 

 

 

Test Driven Reviews

The usual story of Code Reviews is

  • Developer writes code
  • He does a self test (hopefully)
  • Asks for a review from his senior or peer.

My experience is that reviews usually happen pretty late in the development phase. It could just be 1 or 2 days left for the deadline. The deadline could be the end of Dev Phase or end of a Sprint. The review is mostly a gating criteria in a project plan that needs to be done before the code can go to next stage.

By this time it is pretty much late to do any substantial changes in the code. The reviewer may ask for a change – even want a significant change. But by this time the developer has invested a lot in the current code. He not only is reluctant at changing what he thinks is a beautiful code, but is also looking at lots of efforts to test it again. And then there’s that deadline looming before him that will get missed. [There are exceptions]

Let’s say the developer actually does all the changes in the limited time available, what’s the guarantee that it will now actually work? He had tested that it was working before, will it continue to work? Can the reviewer take the risk?

Unit tests should make life easier for all of us. After all, all developers do TDD, right?Well in an ideal world that would be true. Unfortunately we do not live in that world. We are reaching there, but not yet there with the unit tests.

So what’s the way out?

I propose following an approach of Test Driven Review.

The reviewer should make it clear – much before the review phase – that he would be reviewing the code based on the unit tests written. He would not clear the gating criteria unless he sees the tests.

This approach will have the following advantages

  1. Unit tests are compulsorily written – otherwise the gating criteria would not be met.
  2. During review, the reviewer can confirm that the tests indeed do cover all scenarios. If all scenarios are covered and the tests are passing, that would mean the code is functionally correct. The reviewer will only need to concentrate on the code design and the flow.
  3. Code fixes and Code Refactoring will now be safe. As long as the unit tests still run, the changes made haven’t impacted the tested functionality. This will basically provide the necessary safety net for the developer to do changes quickly in the limited amount of time. Both developer and the reviewer will have more confidence of making the changes.

Well, isn’t TDD a better approach than this? Of course it is. The problem is that developers just don’t do it unless they have either a Carrot egging them on or a Stick forcing them to do it. I feel this approach will act like a Stick moving them towards TDD.

What about the approach of “Failing a build if a certain percentage of code coverage is not reached”? Developers are smart and may manage to create test cases that cover a lot of code, but do not really assert the functionality. A 90+ code coverage doesn’t really mean that all functionality has actually been tested.
E.g. – Within a test case you can call a method enclosed in a try/catch block and do not assert anything. That gives you at least 70% coverage out of the box, no sweat.

There are now a lot of code quality tools like PMD, Checkstyle, Findbugs and Sonar available to automate the code quality review.

But there is simply no automated way to validate the usefulness of test cases. Human intervention is still necessary.

And I believe that’s what Code Reviews should focus on.

 

 

 

 

 

 

Equals and Hashcode – An analogy

Tags

[I had written this blog in a previous company that I was working in. Reproducing it here on my personal blog site]

Prologue

I am always surprised by why a simple concept like hashCode() and its contract with the equals() method gets developers confused. And the confusion is not just with beginers of the Java language. In the interviews that I have conducted, I have seen the confusion even with experienced folks.

Most of the time the candidate would have mugged up these two lines

1. If two objects are equal, then they must have the same hash code.
2. If two objects have the same hashcode, they may or may not be equal.

Probe a little deeper and you know they have no clue of what they are talking about.

Personally I always prefer to have analogies for the concepts, that help me remember stuff. I feel mugging up is like RAM – short term and volatile, while analogies are like persistent storage – long term and durable. See I am even thinking of an analogy for analogies.

Anyways, here goes my analogy to remember Equals and HashCode contract.

The “Twin brother” and “Last Name” Analogy

Imagine I gave you the following list of names and asked you to tell me who is the twin brother of Ashish Joshi.

  • Amir Khan
  • Nitin Raichura
  • Yashwant Raut
  • Aayush Joshi
  • Mayuresh Vaze
  • Prem Tewary
  • Amit Joshi
  • Vishal Sharma

Even without knowing who Ashish is or any of the people in this list, you will quickly eliminate all and just keep two “suspects”

  • Aayush Joshi
  • Amit Joshi

What allowed you to eliminate the others and narrow it down to just 2 names?

Well – their last names did not match. What you are implicitly thinking is – “Twin brothers should have the same last name”.

Hashcode allows you to do the exact same thing. It helps you quickly narrow down on the “searchable list”. Thats all there is to it. Nothing more nothing less.

Let us try to re-write the contract between equals and hashcode substituting “twins” for equals and “last name” for hashcode.

  1. If two people are twins, then they must have the same last name.
  2. If two people have the same last name, they may or may not be Twins.

Now these two lines are something you just know by experience. You don’t have to mug it up.

Let us see how you can now think of different aspects of equals and hashCode() with this analogy

Question: Can a hashCode() method just “return 1″ like this

@Override
public int hashCode() { 
    return 1;
}
  • Answer:
    • [Analogy terms] This would mean every person has the same last name. That would be a less interesting world to live in, but there isn’t anything that will break. In fact you would get this experience in Punjab, India where names are like – Amarjeet Singh, Gurpreet Singh, Manjeet Singh, Devinder Singh, Amandeep Singh etc. The Last Name will not result in narrowing down anything and you would have to go through all persons one by one to determine if that person is a twin of some other person.
    • [Actual Answer] Bad coding practice, but why not. Performance Impact? – Yes, a big one. Functional impact?  No. Searching will continue to work, albeit slowly.

 

  • Question: What should be good qualities of a hashCode() method ?
  • Answer:
    • [Analogy terms] What would be a good last name? In our analogy in an ideal world, each family would have a distinct last name. That way only twins can have same last name. However in real world, that is not possible. Practically  it would be good to have as many distinct Last Names as possible so that the searchable list is short enough.
    • [Actual Answer] A good hashing function should be ideally unique. But practically it should be the one that results in minimal collisions. The hash function should distribute the objects across as many distinct hashcodes as possible.

 

I hope this analogy helps in remembering the basic concept without really mugging up the contract.  It is the concepts that help in actual project execution, mugging up may only get you past the first interview round 🙂

What’s The Output?

Tags

A long time ago in a college far far away, young Jedi learning The Force (what else – the C language) would be given a problem -something like the following.

What’s the output of the following?

i=0;

j=i++ + i + i-- + i++ + i++;
k=j-- - j++ + i++;

printf("%d %d %d",i,j,k);

The young Jedi would eagerly figure out the numbers printed by the program and be really proud of their powers !!

Yes, the Force Was With Them.

Well it’s really been A Long Long Time Ago.

Today if someone shows me the same problem and asks me for the output, I would say that the output of that code snippet was

The developer of that code snippet was FIRED !!

Magical Coding is Out, Maintainable Code is the IN thing.

If no one can understand what you are writing, this galaxy is not for you. Find a suitable one Far Far Away.