How to write good software

Here is my theory on an algorithm to build great software :

  1. Figure out how the software ought to work.

    This is the most important part in the software design process. It is important that the user experience be nailed down before we begin all other processes. If we don’t do this first, people will find the easiest way to make the software work. Such an approach may not deliver the best quality experience to the user. It is important to note that it is essential, to involve the users in this step. We need to clearly understand the problems they are facing. How should the optimal solution to their problem work ? Is it even possible with the available resources and at the current state of the art ?

  2. Make it work

    This is the part where you build the software according to the expectations set by the user. At this point you do not have to worry about code quality, performance etc.

  3. Make it better

    In this step you have to make sure that the code is extendable, has high quality tests and is secure

  4. Make it pretty

    In this step, make the software beautiful. Make the text conversational and friendly. Introduce fancy graphics and other visual elements if possible.

  5. Make it fast

    Finally it is time to seek out the worst performing parts of the software and make it fast.

If you follow these steps, and in that order, you should have a high quality piece of software in your hands.


What is polymorphism ?

Polymorphism is touted as one of the awesomest features of Object Oriented Programming. But what exactly is the point of polymorphism ?

Lets take the problem of trying to automate Google search. Lets say your test case is :

  1. Open the browser
  2. Navigate to “”
  3. Type “facebook” to the search text box
  4. Click on “Google Search” button
  5. Wait for the page to load
  6. Check if the results page contain a link to “”

Clearly we need to find some way to drive the browser to do these actions. But how will the automation software know where the ‘search text box’ is ? How will it know where the ‘Google Search button’ is ? So, there is a technology called Xpath that lets you identify a particular element in a web page.

So here is the procedural code that solves the problem ( Language : C ):

int search_google_facebook()
    int test_passed = 1;
    char *search_box_xpath = "//searchbox";
    char *search_button_xpath = "//searchbutton";

    firefox_navigate( "" );
    firefox_type( search_box_xpath, "facebook" );
    firefox_click( search_button_xpath );
    test_passed &&= firefox_search_page_link( "" ):

    chrome_navigate( "" );
    chrome_type( search_box_xpath, "facebook" );
    chrome_click( search_button_xpath );
    test_passed &&= chrome_search_page_link( "" ):

    return test_passed;

Now lets look at the object oriented solution to the problem. Please keep in mind the Liskov Subsitution Principle : base class pointers can point to derived class objects. The code is in Java, so if you are unfamiliar with Java, just keep in mind that classes that implement an interface can be thought of as a derived class of said interface :

public interface BrowserDriver {
    public void navigate( String URL );
    public void type ( String textBoxXpath, String textToType );
    public void click ( String buttonXpath );
    public void waitForPageLoad();
    public boolean searchForLink();

public class FirefoxBrowserDriver implements BrowserDriver {
	public void navigate( String URL ) {
	// Code to navigate Firefox browser to the URL

	public void type ( String textBoxXpath, String textToType ) {
	// Code to type "textToType" into text box identified by textBoxXpath in Firefox

	// etc

public class ChromeBrowserDriver implements BrowserDriver {
	public void navigate( String URL ) {
	// Code to navigate Chrome browser to the URL

	public void type ( String textBoxXpath, String textToType ) {
	// Code to type "textToType" into text box identified by textBoxXpath in Chrome

	// etc

public class GoogleSearchFaceBookTest {

	public static boolean testGoogleSearchFacebook( BrowserDriver driver ) {
		driver.navigate( "" );
		driver.type( "//searchbox", "facebook" ); "//searchbutton" );
		return driver.searchForLink("");



public class TestMain {

	public static void main( String [] args ) {
		BrowserDriver browserDrivers[] = { new ChromeBrowserDriver(), new FirefoxBrowserDriver() };
		for( browserDriver : browserDrivers ) {
			if(!GoogleSearchFaceBookTest.testGoogleSearchFacebook( browserDriver )) {
				System.out.println( "GoogleSearchFaceBookTest has failed!" );



If you have a very large test suites, there are a couple of advantages to this approach :

  1. This code is a lot less copy paste and hence less error prone.
  2. Code is easily extensible : Want to add a new test ? Just add it to the main for loop. New test runs with all supported browsers. Want to add a new browser to the test suite ? Just add the driver object to the browserDrivers array. Your entire test suite now runs against the new browser.

How does this magic happen ? If you look at these lines of code :

driver.navigate( "" );
driver.type( "//searchbox", "facebook" ); "//searchbutton" );
return driver.searchForLink();

you can see that the code behaves differently ( polymorphism ) based on the type of the driver object. If the driver object is of type ChromeBrowserDriver, calls get dispatched to ChromeBrowserDriver methods. If driver is of type FirefoxBrowserDriver, calls get dispatched to FirefoxBrowserDriver methods. This is the power of polymorphism and it allows us to write modular code.

One important question that could come up at this point is : ‘My favorite language is C. Do I need to switch to Java to write object oriented code ?’. And my answer is : No, it is not the language that is important, but the technique. You can find object oriented code in C. Look at the write() system call in Linux :

ssize_t write(int fd, const void *buf, size_t count);

This is an object method operating on the file object pointed to by the “fd” parameter.

Since C is a simpler language compared to Java, if modularity problems are not common in the problems that you solve, use C. I believe we must use the simplest tool that gets the job done. This reduces chances for bugs and creates more performant software.

On the other hand, if modularity problems are common in the problem you are attempting to solve, it maybe helpful to use a language with support for object orientation. For example, if you say that ‘class A implements interface B’ and while implementing class A, if you forgot to implement a method specified in interface B, you get a nice compile time error in Java. In fact, if you use a good IDE, it will report the problem immediately, before you even decide to compile the program.

Ten pieces of advice to managers of software companies; from a programmer

How would you want manage a software company ? Software is unlike many other industries in the sense that it is a creative process. In other industries ( say a Coca-Cola bottling plant ) there is a linear relationship between labor and result. If it takes 1 hour for a person to fill 100 Coca-Cola bottles, it will most probably take him 2 hours to fill the a total of 200 bottles and so on. If you want 200 Coca-Cola bottles filled in an hour, you should therefore employ 2 people. It is fairly predictable how much time it would take to fill 300 Coca-cola bottles with one person : 3. None of this translates well into software. In software, once a software is developed, it is trivial to create a copy of it. Software companies make money by making new things : adding features, fixing bugs etc ( I am excluding SaaS business models for the moment, though they also require new features to stay on top of competition ). One important feature of this type of creative work is that, by its very nature, it is unpredictable. If you know what code will solve your problem, and you know that it will work, typing in the code is the simplest thing in the world. Majority of software development involves figuring out how to solve the problem. And this process is venturing into the unknown, taking educated guesses, trying what works and on failures start fresh. What kind of management does this lend itself into ?

First off, it is pointless to ask people to put more time at work. When you try something and fails, it is important to take a step back and relax. The problem needs to be emptied from your mind for a while so that on the next approach you will not go down the same rabbit hole you went before. Software companies that require employees to put their bums on their seats as much as possible needs to go out of business, and fast.

Secondly, it is very hard ( and most times, impossible ) to estimate how much time it would take to do something. To give you an example, lets say I want you to make me some “Japanese Kuhoo Kuhoo”. I won’t tell you what it is, or how to make it, but I want you to tell me how much time it would take to make it. You don’t know what you would need to make it. You don’t even know if it is a real thing or something I made up entirely to mess with you. How will you know how much time it would take ? You can’t. You can’t plan for the unknown. If you absolutely want to know how much time it would take, please consult an Oracle. Because their estimates can have as much bearing on reality as anyone else’s.

Thirdly, you must never reward drama. Drama is always a sign of dysfunction, not capacity. Imagine two teams. Team 1 is a well run team. There are unit tests for almost all important functionality. Commits that break unit tests are disallowed automatically from nightly builds. Team 2 gives zero fucks to any sort of automated testing. Result is that days before release, testing reveals lots and lots of bugs. Developers are asked to stay back late to fix issues. Management sees that Team 2is toiling away, burning the midnight oil while people from Team 1 goes home on time. Management rewards Team 2 with bonuses. Until of course the house of cards built by Team 2 just crumbles under its own weight.

Fourthly, and this is not specific to software companies. Accountability should never get lost in layers and layers of management. For example, imagine people found critical security issues during testing just before release. Management is not supposed to say ‘We will focus on these trivial stylistic changes which are more visible to my manager and release the software with security problems’. In big companies it is very much possible for this to happen. Managers know that even if word gets out that the software was released with known security defects, the resulting inquiry would probably find nothing.

Fifthly, there should be penalty for risk-avoidance. For example, lets say that an employee comes to internal IT department with a request to install the Operating System on their Solid State Device. The IT department refuses to install it saying that it is a risk for them since they do not know how to configure backups properly. The Operating System being installed on the SSD can save developer time which is valuable to the company. But the problem here is that there is no downside for IT department to refuse the request. They have only upsides. Ideally, there should be a penalty for the internal IT in the company so that if the company is spending the money for an SSD, if IT is refusing to make use of it they should get penalized.

Sixthly, people should not be allowed to screw company for short term gain. For example, a new CEO can cut R&D spending for software companies if those projects would only lead to products in a few years. Cutting those projects would mean that the expenses would be reduced ( with no reduction in immediate profits ). Slump in profits comes a few years later when the company has no more new products coming out of the pipeline by which time the executive would have left the company. This problem can probably be solved by paying the executive even after him leaving the company; based on the performance of the team he used to manage.

Seventhly, responsibilities must be handed off properly. Lets say ‘Project A’ uses library built by ‘Project B’. When ‘Project B’ obsoletes a version of the library, ‘Project A’ must be given permission to take over maintenance of the library. Or the manager for ‘Project A’ should force the engineers to move away from ‘Project B’ library before it goes out of support.

Eighthly, you must not use metrics such as ‘number of cases solved’ as a metric for productivity. This is the Coca-Cola bottle mentality. If you do this, you will get the behavior that you incentivize. People will pick up easier cases since they can be solved faster. This is bad since when faced with a problem, it is the skill of your programmers that will decide how well and in how much time it gets solved. This skill is like any other muscle, it gets better the more you use it. It is probably a better idea to encourage your programmers to pick hard problems. ‘Number of cases solved’ in no way represents the amount of work done : the quality of the solution matters, the complexity of the problem matters.

Ninethly, you mustn’t assume that if you put more people into a project it will run into completion faster. Putting more people into a late project makes it later. See ‘Mythical Man Month’.

Tenthly, you must not waste your employee’s time. People who want to live meaningful lives will rue it when their work is wasted. They want to do a good job and when they see their work is duplicated, or wasted because of say, management indecision, they are less amused. This problem is compounded by the recent ‘Agile Movement’, which has taken to mean, the managers can change their mind whenever they want. Project direction, once set, should only be changed if market conditions change.


Glen and Sally were having coffee at the coffee shop.

“If you could have one wish what would it be ?” Sally asked.

“I would wish to have infinite wishes”, Glen said without hesitation. He had thought of this before.

“I mean apart from that” Sally said.

“I would wish to have another wish without the restriction to have infinite wishes and then wish to have infinite wishes, but I get your point” Glen said. “I would wish for perpetual perfect regeneration with the ability to end my life whenever I please” he continued.

“That is very particular. Why ?” Sally asked.

“Well, first I would have wanted to live forever, but then what would be the point if you age to say 90 and then live in that state forever ? Definitely you would want to stay young. But then, what if someone cuts off your arms and legs ? You wouldn’t want to live like that forever. See, immortality brings its own set of curses. You wouldn’t want to be forced to end your life because your are handicapped. You would want everything to return to normal. So the ideal way to phrase a good immortality wish is ‘perpetual perfect regeneration’. But what if someone caught you and catapulted you into space ? You would float through space forever having nothing to do. So you would probably want to end your life then. You would probably want to do that anyway at some point.”

“But what would you do with immortality ?” Sally had asked.

“Well, first off I would quit my job.” Glenn said with a laugh.

“Of course” Sally laughed “And then what would you do?”

“Well I would go out and learn everything about everything” Glen said.

“Everything ?” asked Sally.

“Yes, everything.” Glen replied “Physics, Chemistry, Philosophy, Psychology, Sociology, Voodoo magic, you name it.”

“And then what ?” Sally asked.

“Well, I have no idea how long that will take” Glen replied “Step two would be to obtain power and money. I bet being immortal would lend itself nicely to doing really dangerous jobs that has a potential for high pay off. But I am really hoping that there would be some connection in all the knowledge that is available in the world that nobody has made. A connection nobody can possibly make in one lifetime. A source of large amount of power.

After that I would have to try and take over. See, I would have lots of time. All I would need to do is wait for right opportunities. I bet the best places to take over first are the war torn areas in Africa where a power vacuum develops every few decades. The point is try to install people who are obliged to you to serve as your puppets.

Form a secret society, with a hierarchical tree like structure. At each level, you have a number of people overseeing the work of one or more people. Anyone power hungry can join, and take a pseudonym. Nobody knows each others name, how many people there are at each level or how many levels there are. You can kind of ask these people to help each other and act as a power broker. It is important to stay away from the light though”

“Why ?” asked Sally.

“Well, that kind of power would simply attract too much attention. I can definitely see people sacrificing their entire lives to make my life miserable if they can detect my involvement” Glen replied.

“OK” Sally was now starting to regret ever having asked the question.

“Well the next step is to optimize” Glen continued on, unaware of the uneasiness developing in Sally, “Obviously, I feel the worst thing in the world is war. When people are constantly fighting each other they have nothing to look forward to. First thing I would do is stop all the wars. When people feel safe, and they know what they build won’t be taken away from them using force, they will start building for the future. Next step is to educate. The benefits of Enlightenment should percolate to the whole world. Just imagine, billions of people in the developing and under-developed nations joining the quest for Scientific Inquiry. How much more the average human condition would improve! How the international productivity would go through the roof!”

“What then ?” asked Sally

“Well, the next step is to expand outwards, of course. Colonize the moon. Colonize Mars. It might be possible to sustain human life in harsh conditions by then. Expand outward. We have no idea how vast the Universe is. I could be doing this for a while”, Glen finished with a smile.

There was a silence. “Do you know what you are planning to do ? You are planning to become God!” said Sally.

“Not really, for all we know God’s powers could be infinite” said Glen. He was an atheist himself, but he did not want to offend Sally’s feelings.

“But do you think that what you asked for is right ?” asked Sally.

“Ah, I thought you wanted to hear about the most interesting wish I could come up with” said Glen taking a sip of his coffee. “I was not thinking about the morality aspect of it. I wouldn’t do this if the opportunity was real. If a genie appeared before me and granted me one wish, I would first ask him ‘Can you go back in time and fix stuff there ?’, if his answer is ‘Yes’, I would wish for ‘Go back to Big Bang and fix everything from there onward, if there was time before that fix that also, if there are other Universes fix everything there as well. FIX EVERYTHING'” he said waving his hands to express his enthusiasm. “If he can’t go back in time and fix stuff – I mean what a crappy genie, right ? – then I would ask him to fix everything instantly”.

“OK” Sally was smiling approvingly now.

“That is the only moral thing you can do, Sally. Everything else is immoral. Since we are just chatting, I just inferred the question as ‘What is the most interesting thing you would wish for?'” said Glen and then he smiled as well.


Sally walked into the room where G.E.N.I.E ( Generic Electronic Nature Influencer Engine ) was housed. She wanted to take Glen’s advice on what to wish for before entering her wish. Sally had felt a huge burden of responsibility when her research was complete and she realized that they could build exactly one machine that could in fact grant someone one actual wish. The machine could not do wish recursion and therefore wishing for more wishes was futile, that was the first thing she tried. But now she had figured out the ideal wish. The only wish any moral person could make.

She pulled out the console for G.E.N.I.E and typed in her wish :


The computer blinked, and then started computing.

After a while it shut down, and changed nothing.

How is The Scientific Method useful ?

Almost everyone knows what “The Scientific Method” is. But people are often confounded by why it is such a big deal. For example, when you ask people to prove their theories, they come up with a variety of evasive maneuvers to get out of doing so. So, what purpose does The Method serve ? Is it applicable always ? Does it have limitations ?

Francis Bacon
Francis Bacon was one of the first men to describe The Scientific Method

To answer these questions, we must first ask ourselves, should we prefer some courses of actions over others ? If you answered ‘yes, we should’, we must ask ourselves : why ? The people who are dedicated to The Scientific Method cares about these things because they consider that these principles have, and will serve them well in life. If you do not wish to improve your life, there is no reason to care about The Scientific Method, nor will it be the only principle that will improve your life. This much should be pretty obvious, that a certain and strong desire to win is a prerequisite to being interested in the Scientific Method. So with that let us build the case for The Scientific Method.

So my first step is to convince you of the idea that “Efficiency Is Always A Good Thing” *. So the first question is what is efficiency ? Imagine that you want to travel from Mumbai to New York and there are two ways of doing so :

1. Get from Mumbai to Frankfurt and then from Frankfurt to New York ( Flight time 23 hours, Price : $5000 )

2. Get from Mumbai to Sydney and from Sydney to New York ( Flight time 32 hours, Price : $2000 )

Do you have all the information you need to figure out what is the more efficient choice ? Nope. You also need to know what is the motivation. If I tell you that you are Bill Gates, the richest man on the planet, then you will probably chose option 1. On the other hand if you are considerably poorer but don’t mind an extra 9 hours of flight time you may chose option 2.

The most efficient solution is that solution which helps you achieve your goal using the least amount of resources possible.

I wanted to drive home the point that efficiency depends on motivation since at this point a lot of interesting questions can come around. For example, you may ask me if I should only say to my children : “Eat your breakfast”, “Do your homework”, “Go to bed”, “Go to school” in the name of efficiency. The answer is no, since in this case, your goal is to try and be a good parent and a strong parental bond developed at an early age is essential for children to turn into healthy adults. Idle talk is an excellent way to form bonds with other human beings.

The simplest idea here is that there are usually multiple ways to achieve your goal and the most efficient ones must always be picked if you care about winning. With that in mind, I am ready to try to convince you how The Scientific Method is useful to us in real life.

The Scientific Method is useful to us in three slightly different but kind of inter-related ways :

1. Since it helps us predict future outcomes, it allows us to make arrangements that can helps us achieve our goals by spending fewer resources ( efficiency ).

Eg : Consider the transitive property of debt. If Alice owes Bob $100 and Bob owes Carol $100, then it is the same as Alice owes Carol $100. Imagine, if Alice and Carol lives together ( or nearby ) and Bob lives halfway around the world. Without our understanding of the transitive nature of debt, Alice would have to travel halfway around the world, give the money to Bob, then they would both have to travel back halfway around the world, and Bob would have to hand the money over to Carol and then go all the way back. What a waste ! But if we can predict that the outcome of the above action and the outcome of Alice giving the money directly to Carol are going to be the same, then we can just choose that option and save two full globe trots. Bob and Alice can use the money saved to buy a new car, or some new fancy clothes !

2. Being able to predict outcomes also helps us control them. For example, imagine a Civil Engineer studying the effect of force on a material. By conducting tests on smaller quantities of a material if he is able to predict in advance what is the amount of cement needed to build a bridge ( or whether to use steel reinforcements ) or how many columns are needed to support a building, then we can build giant buildings and bridges without having to lose many human lives.

3. Since The Scientific Method helps us improve our probabilities ( all the tips and techniques for doing proper science, such as using double blind experiments, computing the consequence of a law and then comparing it to nature, are used to increase the value of “likelihood” { the term P(E|H) } in the diachronic interpretation of Bayes’ Theorem ) it can also help resolve arguments and convince others.

* It is very important to understand the side effects during your chase for efficiency. For example, in the case of flight routes from Mumbai to New York depicted in this post, if everyone where to get rich and always chose Option 1 ( via Frankfurt ) the company running the Australian airways may go into a loss and the people employed by them may get fired and try to make your life difficult for the heck of it. Naturally the probability of this happening is very low in this case, but they must also be accounted for when you are computing your decision.

On free markets

Jawaharlal Nehru had once said “Why do we need 19 brands of toothpaste?

So, I thought about this for a while, since it is a fair question. Producing 19 brands of toothpaste is enormously inefficient. It requires many people doing accounting, marketing and other housekeeping activities which are resources you could divert into the production of other goods and services. Then I realized why : “It eliminates corruption” ( among other inefficiencies ).

I am yet to see a good systemic solution for government corruption. One common solution proposed is to put people to watch the government officials to check if they are corrupt. But of course the problem here is that it creates a new problem : who will watch the watchers ?

Free market is a solution to this problem. Imagine a toothpaste company ( say “Colgate” ) trying to make toothpaste. It requires the supply of 100 Kg of Calcium Carbonate from the rocks in a nearby quarry. The quarry owner agrees to sell this to Colgate for $100. Imagine the supplier in charge of securing the raw materials instead asks the quarry owner to charge the company $200 so that both of them can pocket $50 each. This cost would in turn be borne by the customer purchasing the toothpaste. However, in this case, another company ( say “Pepsodent” ) may be able to obtain the same quantity of Calcium Carbonate for $100 from another quarry and the sell their toothpaste for a lower price. Given two packets of toothpaste with exactly the same quality which one would you choose ? Surely the lower priced one. This should put Colgate out of business and thus end this instance of corruption. Therefore, this provides a systemic incentive to end corruption.

The fall of the politician

Imagine you are a politician trying to gain support for your cause. In due course of this process, you have to argue with someone on whether Mahatma Gandhi was a good man or not ( these things happen, you know ?). You are relying on the assumption that Gandhi was in fact a good person and this is crucial for you to win the argument.

Now, lo and behold, your opponent raises the point : “Gandhi was a criminal”. The trap is set, and you are naive enough to fall into it.

Will Rahul Gandhi now turn crafty ?

The problem here is that your opponent has invoked a cognitive bias we like to call non-central fallacy. Truth be told, Gandhi was a criminal. The British government clearly said that you must not make salt and Gandhi made salt. Therefore, he was a criminal ( he violated the law ). Now there is no time to convince everyone that all the ideas that come into your mind when you hear the word “criminal” does not apply to Gandhi. Therefore, you cannot say that he was the ‘good kind of criminal’. That he violated an unjust law. Since you care about the truth you are unwilling to argue any other way. You lose the argument and therefore lose support for your cause.

But you go home and analyse : “Why did you lose ?”. Here is where you arrive at a difficult and dangerous conclusion : the truth is not enough. People are driven by their emotions, their cognitive biases and their prejudices. It is OK to bend the truth so long as the ends justify the means.

The deceitful politician is born.

— Credit to phantasm for saying “You always get the leader you deserve”