IMagic – The power of interfaces

This one talks about the power of Interfaces, and how polymorphism can make things highly flexible and decoupled. Interface is a simple view of your class-to-be to the outside world, a perfect form of abstraction. Wikipedia says

A protocol or interface is a common means for unrelated objects to communicate with each other. These are definitions of methods and values which the objects agree upon in order to cooperate.

Lets take an example for better understanding. Assume, I am creating my good old calculator again.

public class Calculator{
 public Button[] Buttons;
 public DisplayPanel UserDisplay;
 private int _operand1;
 private int _operand2;
 private char _operator;
 private int calculate(){  
 }
}

Being poor, I can’t afford any staff to work on my jazzy calculator. I have come up with all my classes and stuff, but can’t start working on my calculators logic, as my Calculator has an object of type DisplayPanel, and I will have to complete the implementation of this class in order to use it in Calculator otherwise my compiler will simply keep complaining and won’t let me proceed. But Calculator seems far more interesting to start with than DisplayPanel. So what do I do? You may say, I will write the DisplayPanel class and leave all the functions blank!! Smart 🙂 What about the non-void functions if any? You would return some random value based on the type of the return type of the function. Well, why do all this? I would simply go ahead and replace the type of UserDisplay from DisplayPanel with its interface (say IDisplayPanel).

public interface IDisplayPanel{
 void Show(string displayString);
}
public class Calculator{ 
  public IDisplayPanel UserDisplay; 
  //... 
} 

Now, I can bindass go ahead and keep calling UserDisplay.Show(), without the trouble of keeping my compiler happy. This code will build with no compile errors, but will fail at run time since you can only call a function on a solid class instance, not interfaces. So how do I know if what I have written so far works or not? Well unit tests with mocking is the answer, I would like to defer this topic for a post in the near future.

After showing my Calculator idea to some biggy investors in the silicon valley, I manage to get funding to hire 2 assistants. Yippee, now I can get some work on the DisplayPanel started with their help. I assign this task to Bluto, one of my assistants. While my other assistant, Popeye, has no work for the time being and is enjoying spinach with Olive 🙂 Brutus thinks he has come up with an exciting implementation and even I have finished working on my Calculator

Time to merge the code gentlemen!

Scary??? No, all that we need to do is assign the UserDisplay to a concrete class, the one Brutus wrote, before I make any call to any of its methods. Best place is in the constructor.

public class DisplayPanelByBrutus:IDisplayPanel{
  void Show(string displayString){
  //...
  }
}
public class Calculator{ 
 public IDisplayPanel UserDisplay;
 public Calculator(){
  UserDisplay=new DisplayPanelByBrutus();
  //...
 }
 //...
}

Great !!! All works fine, but….. Brutus, as dumb as he is, came up with a very lame and irritating implementation of the IDisplayPanel, this one throws a big message box (IE Style) to the user with the content to display, that too every time I press any button on the calculator :'( !! Popeye, meanwhile knew how pissed I would be, and had already prepared another implementation that he was ready to show me. Better than I thought, a sleek panel on top of all my calculator buttons to immediately show what key the user presses and the result too. Yes, the windows calculator is a complete rip off of Popeye’s version. Wow!!! Totally wanted to get this into my production code. But code change again!!! Well this time it’s just a one line change, in fact half a line.

public class BakwasDisplayPanelByBrutus:IDisplayPanel{
  void Show(string displayString){
    //...
  }
}

public class AwesomeDisplayPanelByPopeye:IDisplayPanel{
  void Show(string displayString){
    //...
  }
}

public class Calculator{
 public IDisplayPanel UserDisplay;
 public Calculator(){
  //UserDisplay=new BakwasDisplayPanelByBrutus();
  UserDisplay=new AwesomeDisplayPanelByPopeye();
  //...
 }
 //...
}

Hope the IMagic got through to you by now. Interfaces allow us to decouple our implementations. You are not bound to someone’s speed of coding. Before you get working on your code that uses someone’s code all you need to do now is just sit together, analyze and agree upon an interface that you both are comfortable with, and both can proceed peacefully and independently. Also, this allows easy migration from one implementation to the other, imagine if you had to change the implementation in case of concrete classes, you would change the body of all your functions, and if the new implementation turned out to be worse, you don’t even have the old code to rollback to, unless you have taken some backup, which again would be tedious to some extent. Here all you do is just change the constructor, and still both the implementations co-exist, this gives the user a choice as well.

Another, in my opinion more powerful, advantage that interfaces give, is when we are actually dealing with enterprise software that depend on third party pluggable code. (You may want to skip to the end, if you are an absolute beginner). In a more complex aka real-world application, you may not have all the code in the same file, in fact not even in same project. Here all you would have is the interface, which would generally be shared across projects. In such cases, your Calculator class won’t even know there is something called AwesomeDisplayPanelByPopeye, only the classes using this calculator may know about it. Hence your statement

UserDisplay=new AwesomeDisplayPanelByPopeye();

Will give a compile error as the class AwesomeDisplayPanelByPopeye is not present in any of the referenced libraries. In such cases, or even otherwise, a concept named Dependency Injection comes into play. In our case, the Calculator is dependent on IDisplayPanel, we don’t want the calculator to decide which implementation of this interface to use, but let the user of the Calculator decide it instead. This is done in various ways, one of them is through the constructor. We remove the default parameter-less constructor, and instead use a constructor that takes an object of type IDisplayPanel, and assign this object to our UserPanel as follows.

public class Calculator{
 public IDisplayPanel UserDisplay;
 public Calculator(IDisplayPanel someDisplayPanel){
   UserDisplay = someDisplayPanel;
   //...
 }
 //...
}

Now, your code is truly agnostic of the implementation of IDisplayPanel that it will use. You can now have n different Calculators from the single Calculator that you wrote. Today’s world is all about choices, more choice you give, more people will use it 🙂

Calculator PopeyesCalculator = new Calculator(new AwesomeDisplayPanelByPopeye());
Calculator BlutosCalculator = new Calculator(new BakwasDisplayPanelByBrutus());
Calculator YourCalculator = new Calculator(new AwesomestDisplayPanelByYou());
public class AwesomestDisplayPanelByYou:IDisplayPanel{
 void Show(string displayString){
   //...
 }
}

There are many more benefits of interfaces than what I tried demonstrating above. Hoping this helps you in writing better, reusable, efficient and beautiful code =D

OOPs………… !!!!

Most of us have gone through books with various definitions/introductions on Object Oriented Programming, these contain then-jargon like abstraction, polymorphism, inheritance, encapsulation, etc. in the very first chapter. How to easily understand all that when we are just starting? To some, it’s too much of spices when they don’t know what common salt is.

To begin with, all we need to know is a class. Class, in simple words is Kind or Family. Let’s say I have a calculator, I like to call it Jugal's Calculator giving a sense of possession. So now, we ask Jugal's Calculator is of what kind? The simplest kind we can identify without knowing the brand or functionality this calculator gives, would be of kind Calculator. It so happens that John Doe also has a calculator, which he calls JDC. From what we know, JDC also belongs to the family of Calculator. So here, Calculator is our Class and Jugal's Calculator & JDC, which are things of those kind, are called objects or instances of the class Calculator.

Object Oriented Programming, as name suggests, revolves around these things or objects that we just defined.

  • What (but not how) this object can do? (encapsulation)
  • What families does the object belong to? (abstraction)
  • What it is made up of? (composition)
  • Does another object already do a part of what I am supposed to? (inheritance)
  • And more complex (yet interesting) things like Polymorphism, etc

We have very loosely defined these terms for understanding purposes, the real meanings will be clearer as we get a better hang of their usages. I also like to call it Real-World Programming. RWP??? We create data structures/classes with the aim of having an analogy to the real world.

With all that said, let’s see how to create a neat class. Things we need to keep in mind are,

  • What will be the primary objective of the objects of this class?
  • What data will they need to have, in order to do these actions efficiently?

These two questions would allow us to define the public part of the class. I would love to use interfaces here, but want to keep things simple till we make them complex ;). If you think you know the answers to these two questions, think again =D.

So, if we have to design a very simple calculator, which even our great grandfathers might not use, what would be our class(es)? Let’s say, this calculator can only perform add and subtract.

public class Calculator{
 public int Add(int x,int y){  
 } 
 public int Subtract(int x,int y){  
 }
}

And we are all happy? Not me. This wouldn’t be wrong or not serve the purpose, just that it doesn’t translate into the real world analogy concept. How many of you have a calculator that asks for the operator first (Add) and then the two numbers and gives the answer back to you? The way calculators work is to give first operand, give operator and then second operand and get the result.

Lets answer the first question.
Add? Subtract? Add & Subtract? I would say, the primary objective of the calculator is to simply Calculate!! Add & Subtract are merely types of calculations.

Now the second question.
It just needs two operands and an operator.

public class Calculator{
 public int Operand1;
 public int Operand2;
 public char Operator;
 public int Calculate(){  
 }
}

So now are we happy? I ain’t yet. This still isn’t real world. A calculator consists of buttons and a display. This is now real world. So we introduce two more types of objects, Button & Display. This is how OOP is supposed to work. Breaking down responsibilities and delegating them so you only do what is your primary role.

In this new approach, the user doesn’t actually interact with Calculator directly, it uses the buttons, which are part of the calculator. The user can press a button. In fact that is all the user can actually do 🙂 Making all the above class members (Operand1, Operand2, Operator, Calculate()) not directly accessible to the user. Thus, they would all become private and an array of Buttons would be the only thing public to the user. Each button would merely expose a method (say, Press()) for the user to interact. Also there would be DisplayPanel that user can view.

I will refrain from going into the implementation details and aim to highlight the process of coming up with the right classes and not implementing them.

public class Calculator{
 public Button[] Buttons;
 public DisplayPanel UserDisplay;
 private int _operand1;
 private int _operand2;
 private char _operator;
 private int calculate(){  
 }
}

public class Button{
 public void Press(){  
 }
 public String DisplayName;
}

public class DisplayPanel{
 public void Show(string displayString){  
 }
}

A question may arise, that why not break up the Button or the DisplayPanel into smaller classes too? Yes, sure go ahead, but for the purpose of creating the class Calculator, we are only concerned about the Button and the DisplayPanel, that’s the beauty of abstraction. You are least bothered of the implementation. Calculator doesn’t care if the DisplayPanel consists of LEDs or Printer or whatever, it only knows that it can call on the method Show() with the string it wants to display.

This process may appear to be inundating at first but would come naturally, like any spoken language that you know, once put into practice. Also the real life correlation helps others to quickly understand your code and approach.

Mumbai Fighters v/s Devils of Terror

Nothing till now had made an impact as fierce as this one on me that finally forced me to punch in my first logical ( read not-bragging ) blog.
Yes, once again the financial hub of the country, the town where Bollywood resides, the city that never sleeps and my hometown – MUMBAI – has been targeted by the people who for some reason think that they can do anything they want and to whomsoever they want. It’s like not-so-hopefully an ever lasting battle of MUMBAIAITES v/s TERRORISTS in our home ground, which BTW Mumbai leads 3-0, yet they never seem to accept their fate. The first being the not-easy-to-forget “BLACK FRIDAY” 12th March 1993 where there were these series of bombings in Mumbai, that’s were it all started and these M****RFU*KING-TERROR-A**H***s got their morale from. Yet we, the citizens of Mumbai, managed to forget all that and continued living a peaceful life for a few years since then. But unfortunately just like us they also didn’t give up. And then a few years back again they struck back when a bus (I ain’t sure but I guess it was Route 340 ) was bombed in Ghatkopar and then later a train in Mulund and then another huge one. like the ’93 serial blasts, remembered as the Terror Tuesday or 7/11, yes it was 11th July 2006. its been branded on the minds of all the Mumbaikars those existed then, be it a 5 year-kid or a 90 year gr8-gr8-granpa of many kids.
All this being said and done, nothing has improved in Mumbai, at least not the judiciary or the security. Although as citizens we are more aware but the people who need to be the most aware and lead the city don’t seem to follow suit. The police force did catch hold of most of the criminals but after expectedly taking so many years, yet it turns out that they were not the slowest, the Apex Judicatory of the country handsomely took its time to do whatever it should not and not do whatever it should. All this giving rise to more and more encouragements to miscreants to bajaofay the country, saying come kick our butt and will give you the other cheek to kick as well.
And now today, 26th of November 2008, it is happening all over again … open firings at one of the world’s busiest railway station(CST), the heritage Taj Mahal hotel that Mumbai boasts of, the posh Oberoi(Trident) at Nariman, the Queen’s necklace, Colaba causeway… and so many more places. Imagine the extent of their fearlessness that they get into CST station with so many guns and start firing at innocent people and moreover escaping from there unhurt by all the RPF security on the station. For us to digest that incident they do a braver thing by hijacking a Cop-Qualis and start firing at people on the road including media people and people outside the Metro multiplex. And to top all this they occupy the biggest hotels of the city, the Oberoi and Taj. And take hostage of hundreds of people and put the Taj on fire. All this is continuing since the last 14 hours and still going on as I am writing this.
The basic motive behind this seems to be yet unclear. And this time around the terrorists ain’t any bunch of old guys who have lived their life enough and can take bullets to part from the world, but these are a few dozens of twenty odd year youths! Now just think when would they have started training for such a sure shot road map to death mission, 10 yrs or 14 yrs ?? quite possible.

Everything is not over yet, this will go on and on and on … until either we or they give up, exactly its a game of who gives up first… and looking at our opponents it doesn’t seem they’ll give up ever unless we show they what we can do by first of all avoiding such incidents and secondly in such cases no need of having a trial for them, just get all the info from them and hang them.
Enough of emotions from me for the day, I think have to prepare for my exams now 🙁 ain’t in any mood though. But one thing that’s positive from this is that the English Cricket Team has cancelled their current tour half way, giving our cricketers (may be BCCI won’t agree) a well deserved break.. But yes in the long run India’s situation might become like Pakistan where no one wants to go… Hope that never happens
RIP : All those who have been victims of such cruelties and those martyr policemen

My C Programs

This post is only for historical reasons, the owner of the concerned site, TechBirbal, has taken the site down and is no more operational


 

Some of My C – Programs [Courtesy WayBack Machine @ acrhive.org]