This blog is subject the DISCLAIMER below.

Wednesday, March 05, 2008

OOP Design Concepts - Interfaces

What is an interface in OOP?
During the process of designing an application using OOP Paradigm, the application will be designed as a set of classes indicating how objects will be created each with specific status and behavior, as well as defining the ways of interaction between those objects. By this way, almost every class indicates a type(an abstracted data type in a more specific manner).
For example, a class named car indicates an object of type car that has a set of status variables and a set of methods that indicates how other objects can interact with it. Consider that we have a car that have the normal four wheels and another type that uses one wheel in the middle of the car to move!!.
The common behavior between the two types of cars is that they can move, either on 4 wheels or 1 wheel it does not make a difference, all what we care about is that they can move, so, simply we can consider the two cars as "Movable". The word movable indicates the ability of the two objects to move which is an indication of the behavior of them without concerning other details like; the model of the car or even the way they can move. These are interfaces.
Interfaces indicate how certain types of objects have to behave. If we want to indicate clearly how a movable object must behave, we will create an interface with a method named " move" and make every movable object provide how this method will be implemented.
In our example; we will create something like what follows:

public interface iMovable
{
public void move();
}

public class normalCar implements iMovable
{
//actual implementation of the move method declared in iMovable
public void move()
{
//the code required to make a normal car move
}
}

public class weirdCar implements iMovable
{
public void move()
{
//the weird code to make a weird car move
}
}


So, why do we need interfaces?
OOP tries to resemble how objects are defined in the real life, and interfaces are a very logical way of grouping objects in terms of behavior. Suppose that we are making a game that has the normal and the weird car,however, a creative team member came with the idea that we need to make the extra super weird car with no wheels and with the ability to turn to a frog to hide from enemies and many many extra features. If we are not using interfaces, the game logic will need to handle the motion of each car as if they are of different type in spite that logically they share the core common behavior.
Interfaces also enhance abstraction which is a core principal of OOP, design patterns like the factory pattern make a perfect use of interfaces through abstracting objects to know which implementation of a certain object type is provided. Interfaces make it very flexible to change implementations of services specially in multilayer applications, for example; in an application, we have a data base layer that have an object named UserDb which is responsible to get the data of the user from the database, and we have another one named UserTxtFile which retrieves the information from a plain text file.
Each of the user objects can be used by a higher layer to retrieve the user data without any modification to the code, inspect the following code:

public interface iUserInfo
{
string getUserName(int userId);
string getUserAge(string username);
}

public class UserDb implements iUserInfo
{
string getUserName(int userId)
{
//code to retrieve user info from the database
}
}

public class UserTxtFile implements iUserInfo
{
string getUserName(int userId)
{
//code to retrieve user info from the plain text file
}
}

public class UserManager()
{
private iUserInfo userInfo;

public string retrieveUserData(string userName)
{
return userInfo.getUserAge(userName);
}
}


Take a close look at the manager class and you will find that it has a reference variable of type iUserInfo, so, if this reference is provided by a factory method or by any other means, the code of the manager class will be the same regardless what implementation is provided. This approach maximizes flexibilty if some implementations need to be altered during the process of software development, as higher level layers will not be affected at all.
Another benefit of interfaces shows up during the development of large projects by large teams, at which the interface acts as a specification for developers with the set of methods they need to implement in classes of a certain type.

What interfaces are NOT?
- Unless the interface specifies a common behavior, do not create one. A common mistake is to use interfaces just to make some constants visible to objects in different layers.
- Interfaces are not a work around to multiple inhertience.

I hope i could make my points clear enough, and about the super car that turns to a frog ; i think it is a good idea. think about it :) .

18 comments:

soli said...

very nice discussion.
sorry i have a question that may be out of your topic
i need to know what's the difference between interface and abstract class and when to use each of them?
thanks.

Unknown said...

hey , its very nice work but i think i have kinda misunderstanding here . If interfaces are indicators to the behavior without concerning abt details how can it help in the example of the extra super wired car i mean i will have to implement the movement in each class thus if i have WiredCar class i will implement its way of movement ,
Car1 which move normally i will implement its way of movement
car2(assuming it share the same way of movement with car1 & have different behaviors than it)i will also have to implement its movement although its the same as car1
how interfaces helped me here ???? by just saying
that i have a method movement that is shared by the classes
implements it ?????

sorry 4 the long comment

thnx in advance

Shady M. Najib said...

I'm not the author of this post, but I guess I can reply here..

In that case, Samar, you'll use abstract classes to implement the common behavior..

That's on the most abstract level, you'll have your interface, below that in a bit less abstraction level you have your abstract classes which has the common behavior among your lowest level of abstraction (that's WierdCar for eg)..

Youssef Mamdouh said...

thanks shady for ur reply, it is exactly as shady said, it is all about levels of abstraction, and another thing...suppose u have a player that has a car..the class of the player will have a member variable of type car (the interface type) and as long as the game continues he may buy a normal car or a weird one, at either cases, u know that when u want to move the player's car u will find a method named move no matter what implementation class supplied for the car..got me??, u know the general type, and u need anything more....
if we make another car it will extend the same hierarchy and providing the same behavior and the game logic will deal with it the same way as it deals with it as it deals with any other car...
if it is still spaghetti feel free to ask as much as u want.....thanks

Unknown said...

Very good article.
There is one point that you made was obvious: alot of programmer just fancily use interface for multiple inheritance as a workaround. That causes a big frustrated code.
Good job!

Unknown said...

I will say, its really great explanation about interfaces. Even i have been using them for long time but never understood the correct use of them. Thanks for these kind atricles

Anonymous said...

Hi my name is Varun. I just want to ask that whether the class which is implementing the interface needs to define all its methods....
In example here class implementing interface doesnot define all its methods.

Anonymous said...

Hi my name is Varun. I just want to ask that whether the class which is implementing the interface needs to define all its methods....
In example here class implementing interface doesnot define all its methods.

Varun said...

Hi my name is Varun. I just want to ask that whether the class which is implementing the interface needs to define all its methods....
In example here class implementing interface doesnot define all its methods.

Youssef Mamdouh said...

hi varun,
unless the class implementing the interface is abstract it has to implement all the methods. The reason for this, is that abstract classes may not implement some methods and leave them to be implemented by a concrete class, but concrete classes need to implement all the methods.

T S Pawan said...

Thanks

its very usefull and consolidated.

Unknown said...

" a creative team member came with the idea that we need to make the extra super weird car with no wheels and with the ability to turn to a frog to hide from enemies and many many extra features. If we are not using interfaces, the game logic will need to handle the motion of each car as if they are of different type in spite that logically they share the core common behavior."

Sorry but I didn't understand the above line, Can someone please tell me how its difficult to write code without interface in above case? Code for both case(w/interface and w/o interface) would be helpful.

Youssef Mamdouh said...

suppose the main game logic has an if condition on the type of objects it is dealing with, and the condition cares only about if this object can move or not. Using interfaces will make this condition possible in the easiest way;

if( object instanceof Movable)
{
//Code here
}

suppose we did not have interfaces, so we do not have a behavioral description for objects, so, the same code above which cares about the moving behavior will be written many many times for each object type

if (object instanceof car)
{
//code here to handle logic related to the moving behavior
}

if (object instanceof plane)
{
//the same code again
}

even if you type a one condition using '||', every time you add a new type that can move, you will add the check in the condition.

Fraz said...

both this and the abstract class post were very helpful, thanks very much for taking the time to write them.

Anonymous said...

UserTxtFile and UserDB classes result into compile time error because they are not implementing both the methods of interface... basics!!!

Steve roberts : hurghada said...

Hi this is great article...thanks so much

Anonymous said...

very good article
thx

Unknown said...

Hi, Nice description about Interface in Oops concepts.Thanks, its really helped me......

-Aparna
Theosoft