Interfaces in OOPs are very powerful when it is used wisely. One of the best uses of an interface is to decouple the classes or reduces the dependency between two classes. The following example illustrates a scenario where interfaces can be used to decouple two classes, management and employee type classes.
Let us take an example of a company which has a managment entity and other workers like clerks and engineers. Assume that the management wants to find out the manager of these two worker entities from the OOPs point of view.
Bad example.
A naive programmer would implement something like this
class management
{
public string manager(clerk clerkObject)
{
return clerkobject.manager();
}
public string manager(engineer engineerObject)
{
return engineerObject.manager();
}
}
class clerk
{
public string manager()
{
return "Pradeep";
}
}
class engineer
{
public string manager()
{
return "Pramod";
}
}
The above code will return the name of the manager heading the clerk or engineer class of employees. Even though the code returns the correct result, the design is not good from OOPs point of view. A better way would be the following
class management
{
public string manager(IManager managerObj)
{
return managerObj.manager();
}
}
interface IManager
{
string manager();
}
class clerk:IManager
{
public string manager()
{
return "Pradeep";
}
}
class engineer:IManager
{
public string manager()
{
return "Pramod";
}
}
In the above example we have decoupled the managemened class from the Clerk and engineer class, at the same time getting the result that we want.
Tuesday, September 4, 2007
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment