tag:blogger.com,1999:blog-1657193668051217452024-03-12T19:06:14.145-07:00Rudimentary BlocksKrishhttp://www.blogger.com/profile/06674492702273228319noreply@blogger.comBlogger6125tag:blogger.com,1999:blog-165719366805121745.post-16732901257786240922010-02-15T05:54:00.000-08:002010-02-15T05:55:56.413-08:00Why 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 . <br />
<br />
In this post, I will try to discuss some points regarding the interfaces , why we need those and where to use those.<br />
<br />
Following are certain advantages we can achieve using Interfaces.<br />
<br />
1: Separation of Object definition and implementation.<br />
2: Loosely coupled communication between Objects, performance and polymorphism.<br />
3: Reducing the scope of bad design (Not always right)<br />
<br />
<br />
Let us discuss these points one by one. <br />
<br />
<b>Separation of Object definition and implementation:</b><br />
<br />
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 !<br />
<br />
<b>Loosely coupled communication between Objects, performance and polymorphism:</b><br />
<br />
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.<br />
<br />
<i>Class A{<br />
Class B b;<br />
public void setB(B b){<br />
this.b=b;<br />
}<br />
public void doSomething(){<br />
b.doSomething();<br />
}<br />
}</i><br />
<br />
now you can use this class like this<br />
<i>A a=new A();<br />
a.setB(new B());<br />
a.doSomething();</i><br />
<br />
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. <br />
<br />
<i>A a=new A();<br />
a.setB(new C());<br />
a.doSomething();</i><br />
<br />
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.<br />
<br />
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.<br />
<br />
<b>Reducing the scope of bad design (Not always right)</b><br />
<br />
Let's take following example.<br />
<br />
<i>Class A{<br />
<br />
public String getHttpData(String url,String user, Stirng password){<br />
<br />
if(doAuthentication(url,user,password)){<br />
// do rest of the stuff....<br />
}<br />
<br />
<br />
}<br />
<br />
public boolean doAuthention (String url, String user,String password){<br />
// do standard http authentication <br />
}<br />
<br />
}</i><br />
<br />
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 ?? <br />
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.<br />
<br />
<i>Class A{<br />
private Authenticator auth;<br />
public String getHttpData(String url,String user, Stirng password){<br />
<br />
if(auth.doAuthentication(url,user,password)){<br />
// do rest of the stuff....<br />
}<br />
<br />
<br />
}<br />
<br />
public void setAuthenticator (Authenticator auth){<br />
this.auth=auth;<br />
}<br />
<br />
}<br />
<br />
<br />
interface Authenticator {<br />
<br />
public boolean doAuthentication(String url,String userName,String password);<br />
}<br />
</i><br />
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.Krishhttp://www.blogger.com/profile/06674492702273228319noreply@blogger.com0tag:blogger.com,1999:blog-165719366805121745.post-49800946009459882092010-01-26T00:59:00.000-08:002010-01-26T23:39:09.118-08:00Android : working with HttpAll 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.<br />
<br />
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.<br />
<br />
<span style="font-style:italic;">private String getResponse(String url,String parameters, final String method) throws IOException {<br />
HttpURLConnection connection = null;<br />
OutputStreamWriter out = null;<br />
DataInputStream stream=null;<br />
try {<br />
if (url != null && parameters != null) {<br />
/** Opening the connection **/<br />
URL myURL = new URL( url); <br />
/* Open a connection to that URL. */ <br />
connection =(HttpURLConnection) myURL.openConnection(); <br />
// connection = (HttpConnection) Connector.open(url, Connector.READ_WRITE);<br />
/** Set the request method **/<br />
connection.setRequestMethod(method);<br />
<br />
/** Add headers if necessary **/<br />
// Setup data if you want to post some data<br />
if (parameters != null) {<br />
<br />
connection.setRequestProperty("Content-Length", String.valueOf(parameters.length()));<br />
connection.setDoOutput(true); <br />
connection.setDoInput(true); <br />
connection.connect(); <br />
out = new OutputStreamWriter(connection.getOutputStream());<br />
out.write(parameters);<br />
out.flush();<br />
out.close();<br />
}<br />
stream = new DataInputStream(connection.getInputStream());<br />
/** Get the response code **/<br />
httpCode = connection.getResponseCode();<br />
<br />
/** Get the response message **/<br />
switch (httpCode) {<br />
case HttpURLConnection.HTTP_OK:<br />
/** Get the input stream **/<br />
<br />
byte[] data = new byte[512];<br />
int len = 0;<br />
ByteArrayOutputStream buffer=new ByteArrayOutputStream();<br />
while (-1 != (len = stream.read(data))) {<br />
buffer.write(data, 0, len);<br />
}<br />
buffer.flush();<br />
stream.close();<br />
return new String(buffer.toByteArray());<br />
<br />
default:<br />
throw new IOException("Error: HTTP " + httpCode);<br />
}<br />
}<br />
<br />
} catch (IOException e) {<br />
<br />
throw new IOException("Error: HTTP " + httpCode + " " + e.getMessage());<br />
<br />
} finally {<br />
if (out != null) {<br />
try {<br />
out.close();<br />
} catch (IOException e) {<br />
<br />
} finally {<br />
out = null;<br />
}<br />
}<br />
if (stream != null) {<br />
try {<br />
stream.close();<br />
} catch (IOException e) {} <br />
finally {<br />
stream = null;<br />
}<br />
}<br />
if (connection != null) {<br />
try {<br />
<br />
connection.disconnect();<br />
} catch (Exception e) {}<br />
finally {<br />
connection = null;<br />
}<br />
}<br />
}<br />
return null; <br />
}</span><br />
<br />
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.<br />
<br />
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.<br />
<br />
URL represents a uniform resource locator , which is used to open HttpURLConnection.<br />
<span style="font-style:italic;">HttpURLConnection connection =(HttpURLConnection) myURL.openConnection(); </span><br />
Following two lines makes connection available for writing and reading data from connection stream.<br />
<span style="font-style:italic;">connection.setDoOutput(true);</span> // Makes connection available for reading<br />
<span style="font-style:italic;"> connection.setDoInput(true);</span> // Makes connection available for writing.<br />
<br />
Hope this will help to understand http data connection on Android platform.Krishhttp://www.blogger.com/profile/06674492702273228319noreply@blogger.com0tag:blogger.com,1999:blog-165719366805121745.post-21202397804348635232009-01-12T00:23:00.000-08:002010-02-03T11:52:55.989-08:00JavaScript : More than alerts , decoration and validationMost of the developers, especially the web developers think that JavaScript is embedded with web pages to perform Alerts, Decorations and Validation. Is it true?<br />
Here I will make sure to prove it false. Let’s start with OOPs with Java Script.<br />
<br />
<span style="font-weight:bold;">OOPs:</span><br />
<br />
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.<br />
<br />
How to create a class using JS ?<br />
<br />
<span style="font-style:italic;">function Student(name,age){<br />
this.sName=name;<br />
this.sAge=age;<br />
};</span><br />
<br />
How to create object from this class ?<br />
var student=new Student(“Krishan”,31);<br />
Providing getter and setter to class<br />
<span style="font-style:italic;">function Student (name,age){<br />
this.sName=name;<br />
this.sAge=age;<br />
};<br />
<br />
<span style="font-style:italic;"></span>Student.prototype.getName=function(){<br />
return this.sName;<br />
};<br />
<br />
Student.prototype.setName=function(name){<br />
this.sName=name;<br />
};</span><br />
<br />
<b>Note</b>: don’t get confused with prototype . You will get it shortly.<br />
<br />
Using getter and setter<br />
<br />
var student=new Student(“Temp”,20);<br />
student.setName(“Temp1”);<br />
alert(student.getName());<br />
<br />
<span style="font-weight:bold;">JS a Dynamic Language:</span><br />
<br />
Java Script is very dynamic language and do like anything. Following examples explains dynamic nature of JS.<br />
<br />
Assigning method calls to events:<br />
<span style="font-style:italic;"><br />
<javascript version=”xxx”><br />
function callMeOnLoad(){<br />
alert(“Page has been loaded”);<br />
}<br />
onLoad=callMeOnLoad;<br />
</Javascript></span><br />
<br />
Above code will call callMeOnLoad method once webpage is loaded. Same way you can assign function call to other events.<br />
<br />
Assigning methods while constructing the class:<br />
<br />
<span style="font-style:italic;"><br />
function MethodAssignment= function(){<br />
this.callMe=initialize;<br />
}<br />
<br />
function initialize(){<br />
this.name=”xxx”;<br />
}<br />
<br />
Var obj=new MethodAssignment();<br />
Obj.callMe();</span><br />
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?<br />
<br />
<span style="font-weight:bold;">Prototyping:</span><br />
<br />
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<br />
<br />
Let’s say there is a class Student provided by some third party,<br />
<span style="font-style:italic;"><br />
function Student (name){<br />
this.s_name=name;<br />
}<br />
<br />
Student.prototype.getName=function(){<br />
return this.s_name;<br />
}<br />
</span><br />
<br />
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.<br />
<br />
<span style="font-style:italic;"><br />
Student.prototype.setAge=function(age){<br />
this.s_age=age;<br />
};<br />
Student.protype.getAge=function (){<br />
return s_age;<br />
};<br />
</span><br />
<br />
Above code will add setAge and getAge method to Student class and all the objects created from Student class will have these methods. <br />
<br />
prototype property can be used for inheritance as well.<br />
<span style="font-style:italic;"><br />
function BaseStudent (school){<br />
this.s_school=school;<br />
}</span><br />
<br />
Now say <br />
<br />
Student.prototype= BaseStudent;<br />
<br />
Code above will set BaseStudent as super class for Student class.<br />
<br />
I am just starting a habit of writing blog, so have fun .....<br />
<br />
<span style="font-weight:bold;">Koi bekadar Kahiye, Nagina nahi mujhe |<br />
Tere Haaton mai kaid hokar, jeena nahi mujhe ||</span>Krishhttp://www.blogger.com/profile/06674492702273228319noreply@blogger.com0tag:blogger.com,1999:blog-165719366805121745.post-61018562958104329882008-12-26T06:43:00.000-08:002018-12-06T03:12:18.071-08:00deep Jalaya hai Maan kaNeeras ghata parihas udati mere payase jeevan ka |<br />Dhundhli chaya tan man ujla, saar hai kya fir darpan ka ||<br />Smritiyon ke aangan mai, khoya pyar wo bachpan ka|<br />Dil mai khan-khan karta hai ek tuta tukda kangan ka||<br />Yatarth prem ka bhav yahi hai, bishaya nahi hai yeh tan ka|<br />Lekin aise sab bhavon main kab samye raha hai jan jan ka||<br />Aatibrashthi ki hai-hai, kya dosh nahi hai savan ka|<br />Tumse duri ki trashna ne, fir deep jalaya hai maan ka||Krishhttp://www.blogger.com/profile/06674492702273228319noreply@blogger.com0tag:blogger.com,1999:blog-165719366805121745.post-88583132097892218582008-12-11T13:33:00.000-08:002008-12-11T13:40:23.028-08:00Tumhare ... Baad ......Hain Kitne akele aaj tak hum tumhare baad |<br />Is Dil se nahi gaya bahi gum tumhare baad ||<br /><br />Be-Rang ho gayin Ghar ki Dar-o-deewar |<br />Veeranio ne Lahara diye parchum tumhare baad ||<br /><br />Kyon ubharne nahi deta mere naksh ko Ujala |<br />Rafta -Rafta ho gaya to kam tumhare baad ||<br /><br />Keenchti hui saans sa gujra UDASH din |<br />Or Raat bhi Be- Chain hai humdum tumhare baad||Krishhttp://www.blogger.com/profile/06674492702273228319noreply@blogger.com0tag:blogger.com,1999:blog-165719366805121745.post-40302198804583200342008-04-10T09:49:00.000-07:002008-04-10T10:58:51.708-07:00Java Generics -- Part1<span style="color:#000000;">Java Generics provided with JDK5.0 "tiger" is a very powerful feature. It provides following solutions.</span><br /><ol><li><span style="color:#000000;">Code readability</span></li><li><span style="color:#000000;">Robustness </span></li><li><span style="color:#000000;">A way to provide type of collection to compiler.<br />Consider following code</span></li></ol><p><br /><em>public static java.util.Vector getNumbers(){<br />Vector vec=new Vector();<br />vec.addElement(new Integer(10));<br />vec.addElement(new Float(2.5F))<br />return vec;<br />}<br /><br />public static void main(String[] kmj){<br />Vector vec=getNumbers();<br />int size=vec.size();<br />for( int i=0;i<size;i++){<br />Integer int=(Integer) vec.elementAt(i);<br />}}</em></p><p>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.<br />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<br /><br /><em>public static java.util.Vector<integer> getNumbers(){</em></p><em>Vector<integer> vec=new Vector<integer>();</em><br /><em>vec.addElement(new Integer(10));</em><br /><em>vec.addElement(new Float(2.5F)) // Compilation Error</em><br /><em>return vec;</em><br /><em>}</em><br /><em>public static void main(String[] kmj){</em><br /><em>Vector <integer>vec=getNumbers();int size=vec.size();</em><br /><em>for( int i=0;i<size;i++){</em><br /><em>Integer int=vec.elementAt(i);</em><br /><em>}}</em><br /><br /><span style="color:#000000;">This code provides additional advantage over code wirtten above. </span><br /><br /><span style="color:#000000;">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.</span><br /><br /><span style="color:#000000;">Another advantage of above code is that , after looking at method signatures one can identify that what Type of objects , returned collection contains.<br /> </span>Krishhttp://www.blogger.com/profile/06674492702273228319noreply@blogger.com0