Monday, February 15, 2010

Why do we need Interfaces?

While doing programming, specially in OOPs languages we use interfaces. Most of the time we are not very sure, where to use Interfaces .

In this post, I will try to discuss some points regarding the interfaces , why we need those and where to use those.

Following are certain advantages we can achieve using Interfaces.

1: Separation of Object definition and implementation.
2: Loosely coupled communication between Objects, performance and polymorphism.
3: Reducing the scope of bad design (Not always right)


Let us discuss these points one by one.

Separation of Object definition and implementation:

Interfaces provides you the flexibility to separate your Object definition from actual implementation. So what are we gaining here? Well, think that you want to build up a framework where you want the same business logic to be used across J2ME, BlackBerry and Android. Also think that your framework is going to communicate with server for necessary data. As a architect of the framework, you would like to provide definition for the object which is going to talk to server. This will provide you the flexibility to provide different implementation for the communication to server for J2ME, BB and Android,and different team can work on different implementation in parallel. Now you can understand the power of separating you definition from actual implementation !

Loosely coupled communication between Objects, performance and polymorphism:

Two objects A & B are called loosely coupled when we don't need to change the B, when some changes are applied to A. So how interfaces help in this ? Well, Let us think this way. We have a Class A and it Usages class B for some task. Also suppose that you are using Class A and B from a library which is already written and following is the code for coupling between A & B.

Class A{
Class B b;
public void setB(B b){
this.b=b;
}
public void doSomething(){
b.doSomething();
}
}


now you can use this class like this
A a=new A();
a.setB(new B());
a.doSomething();


Up to here everything looks good, but think what if you want to change the behavior of doSomething() in class B. Only choice you have here is to extend a Class C from Class B and change the behavior of doSomething() in Class C and you can use like this.

A a=new A();
a.setB(new C());
a.doSomething();


I can do that easily, but problem is that while creating Object of C , I will be having unnecessary code extended form class B in class C.

If I am going to define B as an interface , It will solve my problem and will reduce dependency of Class A on Class B. Also it will enhance the performance as mermory consumed in case of Interface will be less than memory consumed by extended Class C.

Reducing the scope of bad design (Not always right)

Let's take following example.

Class A{

public String getHttpData(String url,String user, Stirng password){

if(doAuthentication(url,user,password)){
// do rest of the stuff....
}


}

public boolean doAuthention (String url, String user,String password){
// do standard http authentication
}

}


In the above example we have a class which does standard http authentication and gets some data from server. Also suppose this class is part of a library which you want to use for your own project and your HttpServer has a different kind of authentication ??
In this case I can not use this class at all and I will have to write complete code my own. Now lets see magic of interface in this case.

Class A{
private Authenticator auth;
public String getHttpData(String url,String user, Stirng password){

if(auth.doAuthentication(url,user,password)){
// do rest of the stuff....
}


}

public void setAuthenticator (Authenticator auth){
this.auth=auth;
}

}


interface Authenticator {

public boolean doAuthentication(String url,String userName,String password);
}

If you are going to use this code for your library, it can be used for any kind of authentication as implementation for authentication will be provided by end user ( definitely you can provide implementation for standard authorization which can be changed any time by end user) and rest of the stuff will be provided by your library. So interface based programming help for better design.

Tuesday, January 26, 2010

Android : working with Http

All the developers working in Mobile application development, using Java technology, are very much familiar with J2ME & BlackBerry API. Now a days, it is almost impossible to imagine a mobile application without data connection . Reason being that mobile is being used as a smart client for many kind of services, managed by different kind of servers.

While J2ME & BB share same API for data connections (At least at core level and some additional work is required for BB), Android exposes entirely different API for data connections. Following is the example for creating data connection using Android API for http connections.

private String getResponse(String url,String parameters, final String method) throws IOException {
HttpURLConnection connection = null;
OutputStreamWriter out = null;
DataInputStream stream=null;
try {
if (url != null && parameters != null) {
/** Opening the connection **/
URL myURL = new URL( url);
/* Open a connection to that URL. */
connection =(HttpURLConnection) myURL.openConnection();
// connection = (HttpConnection) Connector.open(url, Connector.READ_WRITE);
/** Set the request method **/
connection.setRequestMethod(method);

/** Add headers if necessary **/
// Setup data if you want to post some data
if (parameters != null) {

connection.setRequestProperty("Content-Length", String.valueOf(parameters.length()));
connection.setDoOutput(true);
connection.setDoInput(true);
connection.connect();
out = new OutputStreamWriter(connection.getOutputStream());
out.write(parameters);
out.flush();
out.close();
}
stream = new DataInputStream(connection.getInputStream());
/** Get the response code **/
httpCode = connection.getResponseCode();

/** Get the response message **/
switch (httpCode) {
case HttpURLConnection.HTTP_OK:
/** Get the input stream **/

byte[] data = new byte[512];
int len = 0;
ByteArrayOutputStream buffer=new ByteArrayOutputStream();
while (-1 != (len = stream.read(data))) {
buffer.write(data, 0, len);
}
buffer.flush();
stream.close();
return new String(buffer.toByteArray());

default:
throw new IOException("Error: HTTP " + httpCode);
}
}

} catch (IOException e) {

throw new IOException("Error: HTTP " + httpCode + " " + e.getMessage());

} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {

} finally {
out = null;
}
}
if (stream != null) {
try {
stream.close();
} catch (IOException e) {}
finally {
stream = null;
}
}
if (connection != null) {
try {

connection.disconnect();
} catch (Exception e) {}
finally {
connection = null;
}
}
}
return null;
}


Code above shows that how to use the API available from Android to open a data connection and fetching the data.Though return of data may vary based on the specific need and implementation can be changed accordingly.

Main difference between J2ME and Android, in terms of API is , J2ME uses generic connection framework for any kind of data connection while Android uses standard classes(URL & HttpURLConnection) from java.net (J2SE) package.

URL represents a uniform resource locator , which is used to open HttpURLConnection.
HttpURLConnection connection =(HttpURLConnection) myURL.openConnection();
Following two lines makes connection available for writing and reading data from connection stream.
connection.setDoOutput(true); // Makes connection available for reading
connection.setDoInput(true); // Makes connection available for writing.

Hope this will help to understand http data connection on Android platform.