Posts Tagged ‘coding to an interface’

Coding to Interfaces

December 18, 2010

Coding to an interface rather than to implementation. This makes your software/application easier to extend. In other words, your code will work with all the interface’s subclasses, even ones that have not been created yet.

Anytime if you are writing code that interacts with subclasses, you have two choices either; your code directly interacts with subclasses or interacts with interface. Like this situation, you should always favor/prefer to coding to an interface, not the implementation.

I have created a simple example with JDK classes & interface which demonstrates its benefits.

CodingToAnInterface.java

 import java.util.Hashtable;
 import java.util.LinkedHashMap;
 import java.util.Map;

 public class CodingToAnInterface {

 public static void main(String[] args) {
 // Coding to a class : Creating new instance of Hashtable & Assign it to the class.
 Hashtable subject = new Hashtable();
 CodingToClass c2c = new CodingToClass();
 subject = c2c.addSubject(subject);
 System.out.println("CodingToClass : Hashtable : subject : "+subject);

 // Coding to an interface : Creating new instance of Hashtable & Assign it to the Map interface object.
 Map subj = new Hashtable();
 CodingToIntf c2i = new CodingToIntf();
 subj = c2i.addSubject(subj);
 System.out.println("CodingToInterface : Instantiated Hashtable : subject : "+subj);

 // Now, we have a requirement to show subjects in the order it was inserted. Let’s make a simple change from Hashtable to LinkedHashMap.
 subj = new LinkedHashMap();
 subj = c2i.addSubject(subj);
 System.out.println("CodingToInterface : Instantiated LinkedHashMap : subject : "+subj);
 }
 }

 class CodingToClass{
 // Method argument & return type are defined with class name Hashtable. This allows only Hashtable class as parameter.
 public Hashtable addSubject(Hashtable subject) {
 subject.put("Subject1", 50);
 subject.put("Subject2", 70);
 subject.put("Subject3", 60);
 subject.put("Subject4", 80);
 return subject;
 }
 }

 class CodingToIntf{
 // Method argument & return type are defined with interface Map. This allows to send various possible interface subclasses.
 public Map addSubject(Map subject) {
 subject.put("Subject1", 50);
 subject.put("Subject2", 70);
 subject.put("Subject3", 60);
 subject.put("Subject4", 80);
 return subject;
 }
 }
 

Output

CodingToClass : Hashtable : subject : {Subject4=80, Subject3=60, Subject2=70, Subject1=50}
CodingToInterface : Instantiated Hashtable : subject : {Subject4=80, Subject3=60, Subject2=70, Subject1=50}
CodingToInterface : Instantiated LinkedHashMap : subject : {Subject1=50, Subject2=70, Subject3=60, Subject4=80}

In the above example, initially assigned Hashtable object to interface Map object instead of Hashtable class. Later, we have a requirement to show the subjects in the order we have inserted into it. So we need to change the code and this can be easily achieved here by simply changed the instantiation part from Hashtable to LinkedHashMap without touching addSubject part.
However in coding to class, we have to change all the places where Hashtable is being used.

Instead of your code being able to work with only specific subclass called Hashtable, you are able to work with more generic Map interface. In future, it’s easier to change into some other sub class of Map interface.

Advantages

  • App/Software is easier to extend
  • Adds Flexibility to your App.
  • Helps to maintain the loose coupling of code.

Thread vs Runnable

December 10, 2010

Thread is a block of code which can execute concurrently with other threads in the JVM. You can create and run a thread in either ways; Extending Thread class, Implementing Runnable interface.

Both approaches do the same job but there have been some differences. Almost everyone have this question in their minds: which one is best to use? We will see the answer at the end of this post.

The most common difference is

  • When you extends Thread class, after that you can’t extend any other class which you required. (As you know, Java does not allow inheriting more than one class).
  • When you implements Runnable, you can save a space for your class to extend any other class in future or now.

However, the significant difference is.

  • When you extends Thread class, each of your thread creates unique object and associate with it.
  • When you implements Runnable, it shares the same object to multiple threads.

The following example helps you to understand more clearly.

ThreadVsRunnable.java


class ImplementsRunnable implements Runnable {

 private int counter = 0;

 public void run() {
 counter++;
 System.out.println("ImplementsRunnable : Counter : " + counter);
 }
 }

 class ExtendsThread extends Thread {

 private int counter = 0;

 public void run() {
 counter++;
 System.out.println("ExtendsThread : Counter : " + counter);
 }
 }

 public class ThreadVsRunnable {

 public static void main(String args[]) throws Exception {
 //Multiple threads share the same object.
 ImplementsRunnable rc = new ImplementsRunnable();
 Thread t1 = new Thread(rc);
 t1.start();
 Thread.sleep(1000); // Waiting for 1 second before starting next thread
 Thread t2 = new Thread(rc);
 t2.start();
 Thread.sleep(1000); // Waiting for 1 second before starting next thread
 Thread t3 = new Thread(rc);
 t3.start();

 //Creating new instance for every thread access.
 ExtendsThread tc1 = new ExtendsThread();
 tc1.start();
 Thread.sleep(1000); // Waiting for 1 second before starting next thread
 ExtendsThread tc2 = new ExtendsThread();
 tc2.start();
 Thread.sleep(1000); // Waiting for 1 second before starting next thread
 ExtendsThread tc3 = new ExtendsThread();
 tc3.start();
 }
 }

Output of the above program.

ImplementsRunnable : Counter : 1
ImplementsRunnable : Counter : 2
ImplementsRunnable : Counter : 3
ExtendsThread : Counter : 1
ExtendsThread : Counter : 1
ExtendsThread : Counter : 1

In the Runnable interface approach, only one instance of a class is being created and it has been shared by different threads. So the value of counter is incremented for each and every thread access.

Whereas, Thread class approach, you must have to create separate instance for every thread access. Hence different memory is allocated for every class instances and each has separate counter, the value remains same, which means no increment will happen because none of the object reference is same.

When to use Runnable?
Use Runnable interface when you want to access the same resource from the group of threads. Avoid using Thread class here, because multiple objects creation consumes more memory and it becomes a big performance overhead.

Apart from this, object oriented designs have some guidelines for better coding.

  • Coding to an interface rather than to implementation. This makes your software/application easier to extend. In other words, your code will work with all the interface’s subclasses, even ones that have not been created yet.
  • Interface inheritance (implements) is preferable – This makes your code is loosely coupling between classes/objects.(Note : Thread class internally implements the Runnable interface)

Example: coding to an interface.

Map subject = new HashMap();

Assigning HashMap object to interface Map,  suppose in future if you want to change HashMap to Hashtable or LinkedHashMap you can simple change in the declaration part is enough rather than to all the usage places. This point has been elaborately explained here.

Which one is best to use?

Ans : Very simple, based on your application requirements you will use this appropriately. But I would suggest, try to use interface inheritance i.e., implements Runnable.

Example : 

Map subject = new HashMap();

Assigning HashMap object to interface Map,  suppose in future if you want to change HashMap to Hashtable or LinkedHashMap you can simple change in the declaration area is enough rather than to all the usage places. I will explain this elaborately in the upcoming post.