Saturday, May 8, 2010

Choosing between Abstract Class and Interfaces...

Before I take the topic head on head, let’s understand, or I should say re-understand, what an object oriented programming language has to offer and why it’s preferable in most of the real world software development cases. While citing advantages and positive aspect of java in particular and Object oriented programming in general I would not consider any serious comparison with the procedural languages like c etc. As I believe it may be out of track for the topic I have chosen. As we all know we can model anything which we can see/feel/foresee/want to see etc as an object, this is how our world is planned or organized.... Confused! Lets take some instances....
I say I am working with a ‘private company’ called ‘NDS’. Look at the lines, that how we mostly tell to the people who ask us what we do? Do you see the important words... What exactly we have done in this sentence. We said we are working with a ‘Private Company’, which is a type of classification for generalised thing called ‘company’. So we can model the hierarchy as follows:-


Company --------> Private Company ---------> NDS



But do we see any of these in real world? I mean show me something just an entity called Company....You will beat me till I die for asking this question :P.
But If I ask you to show me anything which can be considered as private company..then you can show me a lot of these. Right! Same goes true for Company also....you can show a lot of real life entities which can be considered as Company.
So we know that though we cannot see PrivateCompany itself....We can see something which is a TYPE-OF PrivateCompany and hence, a TYPE-OF Company.
Now while modelling this relationship in programming can we make an abstract class called Company and an other Abstract Class PrivateCompany extending Company. Now we can make a concrete class which can be instantiated as NDS. Its very very simple description of what can be done as we are not considering behaviour of the Company and PrivateCompany nor we are going deep into analysing these but then also we can see how easily we modelled the real world scenario in an object oriented design    . This is what we lack in procedural languages :- Easy and simple modelling of real life objects in coding/design. This is one of the good features which OOP offers and it is one of the biggest reasons why OOP is so famous in software development community. So we are done with small and sweet warm up and time has arrived to go into deep with the concept of Abstract class and Interfaces in OOPs

What is an abstract? Well, most of us misunderstand the meaning of abstract as far as programming is concerned. Think what abstract means in day to day life? Remember our standard 3-4 english questions
“Give an abstract of your long journey on a train. 4 marks” ;)
In simple words, Abstract means brief description/ part of /summary . What we programmers think about abstract is ‘hiding’. We think that anything has been made abstract for hiding but true is that something has been made abstract for ‘exposing’ HOW? Let us find it out. See above English question, it meant that you have to write a brief description of any of your long train journey. When you write that what you do? You hide the information or you expose the information? You expose the information.....right! But you expose only what is IMPORTANT and REQUIRED. Same goes right for programming, when you make something abstract you actually expose it to the outer world for implementation but at the same time you strictly tell them what the method/class is supposed to do i.e. signature and leave it to others on how they want to implement them. Amazed!!!

If you have got this meaning of ABSTRACT correctly, you will find things pretty simple and easy from here. One thing which we should never forget is that both Interfaces and Abstract Classes are using ABSTRACT concept i.e. expose the usage and leave the actual implementation. If you want an Interface then make any abstract class or concrete class pure Abstract i.e. only expose the signature (and eventually the expectation i.e. expected end result...) but not the implementation. I am not going to tell the syntax of abstract class or interface here, rather I expect you all to be well versed with it.

Everyone knows HOW to write and WHAT to write while writing interfaces and abstract classes. Let’s talk about WHERE to use and WHY to use these. “Life is simple, only we make it complicated”. So before I make it a bit complicated I should give the simple rule which can be consulted while thinking about interfaces and abstract classes:
“USE AN ABSTRACT CLASS WHEN YOU FIND THAT AN OBJECT WILL ‘BORN’ AND ‘DIE’ AS AN INSTANCE OF THAT CLASS, MAKE AN INTERFACE IF YOU FIND THAT OBJECT WILL NOT BORN AS A TYPE OF THE INTERFACE BUT DURING ITS LIFE TIME IT MAY PLAY A ‘ROLE’ WHICH REQUIRE IT TO BE A TYPE OF THE INTERFACE”
Well, the simple rule seem to be a bit complicated in itself so let us go for complicated description to understand this simple rule ;) ;) ;) just kidding....Let us elaborate the rule. I am sure that if I will be able to explain this rule appropriately then only thing you will require afterwards is this simple rule and not the description 

I born as a Human Being and it have been confirmed by the world that I am a human being as I fulfil all criteria of being an Human. So the only thing which the outer world was aware of me is that I am a human and hence they expect me to behave purely like human. They knew how human behave or what human behaviour should be. How? Because god has published API’s and java doc for human class :P :P sorry...I mean the world has seen human for long. It knows how human look like, how they conduct, how they talk, and other such complicated behaviours. It is more or less like knowing the API doc for human class. You know that if you are going to give milk to human and if this human is hungry it will drink it using its hand and mouth unlike any Dog which will use only its mouth/tongue.
Most of you have already got this point that if there is some class which I may belong to is human. But human can be again classified accurately among three categories and I will be taking only two of them for this example. MAN and WOMAN. I am a boy and I will fall to Man category. Human class should be concrete as Man and Woman seems to differ a lot and are more complete classification than Human itself. So what we can do is that we can take common properties of Man and Woman, Put them in Human Class.But Man and Woman completely divides the whole Human in exactly two parts and after this classification there will be none left which cannot be put either under Man or Woman. So what I am trying to say is that all Human are going to be either a Man or Woman i.e. We will never need to instantiate any object of type Human but only Man and Woman. So here We got the reason to not keep Human as concrete class as someone latter may instantiate it and it will be against nature law and hence We will have to make it abstract class. We got our abstract class called Human which will be extended by the concrete classes Man and Woman. GOOD ENOUGH....BUT QUESTION IS WHY CAN NOT WE MAKE Human AN INTERFACE AS IN ANY CASE WE DO NOT REQUIRE IT TO INSTANTIATE????
Here comes the first part of the rule which I gave early.
USE AN ABSTRACT CLASS WHEN YOU FIND THAT AN OBJECT WILL ‘BORN’ AND ‘DIE’ AS AN INSTANCE OF THAT CLASS
Abstract Class is what the object will born like and will eventually die like. I born as Human but can I die like tiger. NO ...No way Its not possible. Once born as Human I am going to remain or remembered as Human forever. This identity of being Human is tightly coupled with me and I cannot change this fact. Same goes for the code. Once an object has been instantiated as a type of a class, it should and it will be always of that type. If you will try to play with its original type then chances are there that you may corrupt the whole design and may get exceptions like ClassCastException etc. Interfaces do not contain any implementation but we know that Abstract Classes can have some implementation. There will be a lot of common code in Man and Woman which can directly got to Human but it is only possible if the class is an Abstract Class. Then where to use interface?
I am a man, so what big deal!!! Think what all we did right from the childhood till date. We went to school, college, played cricket for school team, started working in a PrivateCompany etc. So should these all functionality like playing cricket, studying etc. Should go into Man class or Human Class? Well not definitely in Man class as Woman also does similar activities. Then in Human abstract class should contain all these....But i know a lot of human who does not do any of these or some of these, and if we keep at Human Abstract Class then through inheritance all will get these which is not at all right! Okay then what to do?
Let’s analyze the problem, what we did when we went to school....Studied. What noun can be used for us when we were studying in school? STUDENT right? No matter a girl or a boy, in school we have been referred as Student. Can we say that we played the role of a student when we were in the school? Yes...and similarly, we can say that we play role of a son, employee, student, teacher, actor, model etc.
Now remember the second line of the rule.
MAKE AN INTERFACE IF YOU FIND THAT OBJECT WILL NOT BORN AS A TYPE OF THE INTERFACE BUT DURING ITS LIFE TIME IT MAY PLAY A ‘ROLE’ WHICH REQUIRE IT TO BE A TYPE OF THE INTERFACE
So we have our reason to make an interface each for these all roles which we play for short or long span . We may have an interface called Son which will have abstract methods applicable for this role. Now only those who may play this role can implement it. Man may implement this interface but can Woman also do the same....hmmmm not exactly. They may require a new interface called Daughter.
These all roles does not put any implementation but leave it on other classes to implement. Lets say that both Man and Woman has implemented Student interface and there be a method wearSchoolDress(). Now do you think that both will wear same dresses :P :P nops... So its upto the implementing classes that how they want to to something but at the end they should stick to the API signature and expectation. For example, though boys will wear pant, shirt, tie, shocks and shoe but at the end of the API call they should be well dressed   otherwise they will be sent back from the school :P :P.

With this example I would like to conclude the blog. I would love to know more on this from the readers of this blog and will appreciate any piece of suggestion whole heartily.

CHEERS,