RSS

Program to an interface, not an implementation.

07 Apr

In Software Development process more time is spent on maintaining the code rather than its development and during this period there may be requirement of new classes. By Programing to Interfaces your application/code is always open for modification without much code change.

Like if you coded to concrete classes then your code will look something like this

   
 
public ProcessedTea processTea(Tea tea){  
ProcessedTea processedTea = tea.getProcessedTea();  
return processedTea;  
 }  

But if you program to Interfaces then it can be made generic

      

public ProcessedFood processFood(FoodItem foodItem){  
ProcessedFood processedFood = foodItem.getProcessedFood();  
return processedFood;  
}  

UML Diagram:

Here FoodItem is an Interface and rest of the classes like Tea, Coffee etc implements it.

Now if there is any new addition of any foodItem/Beverages then its a lot easier for you to process it as the method processFood(FoodItem foodItem) takes an implementation of FoodItem. On the other hand if you have programmed to concrete classes like the code given at first then you have to write new method for every food type.

Hope it makes clear that why programming to interfaces is more useful as compared to program to concrete classes.

Advertisements
 
1 Comment

Posted by on April 7, 2010 in Design Patterns, Java

 

Tags: ,

One response to “Program to an interface, not an implementation.

  1. elbek

    February 1, 2012 at 3:02 pm

    nice explanation

     

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: