Monday, February 15, 2010
Why do we need 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
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.
Monday, January 12, 2009
JavaScript : More than alerts , decoration and validation
Here I will make sure to prove it false. Let’s start with OOPs with Java Script.
OOPs:
Java Script supports OOPs. Many of the developer think that JS (JavaScript) is derived from JAVA which is not true. JAVA is a language which is compiled while JS is an interpreted language.
How to create a class using JS ?
function Student(name,age){
this.sName=name;
this.sAge=age;
};
How to create object from this class ?
var student=new Student(“Krishan”,31);
Providing getter and setter to class
function Student (name,age){
this.sName=name;
this.sAge=age;
};
Student.prototype.getName=function(){
return this.sName;
};
Student.prototype.setName=function(name){
this.sName=name;
};
Note: don’t get confused with prototype . You will get it shortly.
Using getter and setter
var student=new Student(“Temp”,20);
student.setName(“Temp1”);
alert(student.getName());
JS a Dynamic Language:
Java Script is very dynamic language and do like anything. Following examples explains dynamic nature of JS.
Assigning method calls to events:
function callMeOnLoad(){
alert(“Page has been loaded”);
}
onLoad=callMeOnLoad;
Above code will call callMeOnLoad method once webpage is loaded. Same way you can assign function call to other events.
Assigning methods while constructing the class:
function MethodAssignment= function(){
this.callMe=initialize;
}
function initialize(){
this.name=”xxx”;
}
Var obj=new MethodAssignment();
Obj.callMe();
Note that this.name=”xxx” in initialize function, 'this reference' is pointing to obj in above code as initialize method is assigned to callMe method and will be invoked when ever obj.callMe() is invoked. Is it useful for providing same function in more than once class, with same behavior?
Prototyping:
Prototyping is a very strong feature from JavaScript and provides extensibility. Suppose you have a already written java script class and your want to extent it's functionality without making any change in the original class, I show you how to do that
Let’s say there is a class Student provided by some third party,
function Student (name){
this.s_name=name;
}
Student.prototype.getName=function(){
return this.s_name;
}
This class only provides name to a student, if you also want to have age in this class then you have to extent this class using prototype property of class. Please go through the code below.
Student.prototype.setAge=function(age){
this.s_age=age;
};
Student.protype.getAge=function (){
return s_age;
};
Above code will add setAge and getAge method to Student class and all the objects created from Student class will have these methods.
prototype property can be used for inheritance as well.
function BaseStudent (school){
this.s_school=school;
}
Now say
Student.prototype= BaseStudent;
Code above will set BaseStudent as super class for Student class.
I am just starting a habit of writing blog, so have fun .....
Koi bekadar Kahiye, Nagina nahi mujhe |
Tere Haaton mai kaid hokar, jeena nahi mujhe ||
Friday, December 26, 2008
deep Jalaya hai Maan ka
Dhundhli chaya tan man ujla, saar hai kya fir darpan ka ||
Smritiyon ke aangan mai, khoya pyar wo bachpan ka|
Dil mai khan-khan karta hai ek tuta tukda kangan ka||
Yatarth prem ka bhav yahi hai, bishaya nahi hai yeh tan ka|
Lekin aise sab bhavon main kab samye raha hai jan jan ka||
Aatibrashthi ki hai-hai, kya dosh nahi hai savan ka|
Tumse duri ki trashna ne, fir deep jalaya hai maan ka||
Thursday, December 11, 2008
Tumhare ... Baad ......
Is Dil se nahi gaya bahi gum tumhare baad ||
Be-Rang ho gayin Ghar ki Dar-o-deewar |
Veeranio ne Lahara diye parchum tumhare baad ||
Kyon ubharne nahi deta mere naksh ko Ujala |
Rafta -Rafta ho gaya to kam tumhare baad ||
Keenchti hui saans sa gujra UDASH din |
Or Raat bhi Be- Chain hai humdum tumhare baad||
Thursday, April 10, 2008
Java Generics -- Part1
- Code readability
- Robustness
- A way to provide type of collection to compiler.
Consider following code
public static java.util.Vector getNumbers(){
Vector vec=new Vector();
vec.addElement(new Integer(10));
vec.addElement(new Float(2.5F))
return vec;
}
public static void main(String[] kmj){
Vector vec=getNumbers();
int size=vec.size();
for( int i=0;i<size;i++){
Integer int=(Integer) vec.elementAt(i);
}}
If you compile above programme it compiles successfully but at runtime it fails. Now a obvious question may be that if a developer is writing code himself then he will be aware of code but at the same time consider a case where a large project is executed and work is divided into modules so it is always possible that you will not be aware of code and will call method directly.
Another case is where you have a large programm and you do not have much documentation available for code and at many places you have methods which return Collections. In this case it is very difficult to identify , what Type of object a particular collection contains, in such scenarios java Generics help you a lot as it increases code redability. Consider following code
public static java.util.Vector
vec.addElement(new Integer(10));
vec.addElement(new Float(2.5F)) // Compilation Error
return vec;
}
public static void main(String[] kmj){
Vector
for( int i=0;i<size;i++){
Integer int=vec.elementAt(i);
}}
This code provides additional advantage over code wirtten above.
This does tells you at compile time only that you code is not type safe. One can have argument that collection should store all type of object. From my point of view Collection are not there for storing multiple type of objects but they are for storing multiple Objects of same Type and help to mange those Object properly.
Another advantage of above code is that , after looking at method signatures one can identify that what Type of objects , returned collection contains.