Understanding Dependency Injection and its Importance, A tutorial

Understanding Dependency Injection and its Importance

Any application is composed of many objects that collaborate with each other to perform some useful stuff. Traditionally each object is responsible for obtaining its own references to the dependent objects (dependencies) it collaborate with. This leads to highly coupled classes and hard-to-test code.

For example, consider a `Car` object.

A `Car` depends on wheels, engine, fuel, battery, etc. to run. Traditionally we define the brand of such dependent objects along with the definition of the `Car` object.

Without Dependency Injection (DI):

  class Car{  
    private Wheel wh = new NepaliRubberWheel();  
    private Battery bt = new ExcideBattery();  
    //The rest  
   }  

Here, the `Car` object *is responsible for creating the dependent objects.*

What if we want to change the type of its dependent object - say `Wheel` - after the initial `NepaliRubberWheel()` punctures?
We need to recreate the Car object with its new dependency say `ChineseRubberWheel()`, but only the `Car` manufacturer can do that.

 Then what does the `Dependency Injection` do for us...?


When using dependency injection, objects are given their dependencies *at run time rather than compile time (car manufacturing time)*.
So that we can now change the `Wheel` whenever we want. Here, the `dependency` (`wheel`) can be injected into `Car` at run time.

After using dependency injection:

Here, we are **injecting** the **dependencies** (Wheel and Battery) at runtime. Hence the term : *Dependency Injection.* We normally rely on DI frameworks such as Spring, Guice, Weld to create the dependencies and inject where needed.

   class Car{  
    private Wheel wh; // Inject an Instance of Wheel (dependency of car) at runtime  
    private Battery bt; // Inject an Instance of Battery (dependency of car) at runtime  
    Car(Wheel wh,Battery bt) {  
      this.wh = wh;  
      this.bt = bt;  
    }  
    //Or we can have setters  
    void setWheel(Wheel wh) {  
      this.wh = wh;  
    }  
   }  

The advantages/benefits of dependency injection are:

  • decoupling the creation of an object (in another word, separate usage from the creation of object)
  • ability to replace dependencies (eg: Wheel, Battery) without changing the class that uses it(Car)
  • promotes "Code to interface not to an implementation" principle
  • ability to create and use mock dependency during a test (if we want to use a Mock of Wheel during test instead of a real instance.. we can create Mock Wheel object and let DI framework inject to Car)

Understanding Importance of Interface, Inheritance...... OOP concepts in a different way !

Lets talk about some fundamentals of Object Oriented Design concepts in a different way...
1.IS A - Inheritance
A super class for Animal

class Animal {
int legs;
String name;
public Animal(int legs, String name) {
  this.legs = legs;
  this.name = name;
}
public void walk() {}
}

Creating Cow class, a type of Animal

class Cow extends Animal {
public Cow(int legs, String name) {
  super(legs, name);
}
}

In the example above,
Cow is a subclass of Animal because Cow inherits from Animal. So inheritance is ISA relationship. You see the walk() methods is already defined for Animal and we don't need to defined them again and again.
2. Has A - Member Field
Lets create Brain...

class Memory {
 int size;
 public void loadIntoMemory(Object anything) {}
 public boolean isInMemory(Object suspect) {
  return true;
}
}

Adding brain to Dogs' head.
class Dog extends Animal{
  Memory dogMemory;
}

Dog is obvioulsy an Animal and a Dog has some Memory called dogMemory. Hence, HAS-A relation is defined by a member field.
3. Performs - Interface
Lets introduce a interface IHelp.

interface IHelp {
  void doHelp();
}

Creating A Dog
class Dog extends Animal implements IHelp {
  private Memory dogMemory;
  public Dog(int legs, String name) {
  super(legs, name);
}
@Override
public void doHelp() {
  if (dogMemory.isInMemory(new Object())) {
  walk();
  findSuspect();
 }
}
private void findSuspect() {}
}

Here Dog is an Animal, it has Memory and it can Help. We can ensure a Dog can help by implementing IHelp interface.

Something More
The benefit of IHelp interface is that we can get help from all Animals by using same interface methods.
For example , lets create a Horse Class

class Horse extends Animal implements IHelp{
public Horse(int legs, String name){
  super(legs,name);
}
@Override
public void doHelp() {
  carryHuman();
}
private void carryHuman();
}



Getting help from Horse
Horse aHorse= new Horse(4,"Acorn");
horse.doHelp();


and for getting help from Dog
Dog aDog= new Dog(4,"Puppy");
aDog.doHelp();


You see we can get help from these Animals from same method doHelp();.
Its the fun of Object Oriented Design.......
Enjoy !!!!!

Some Popular, Interesting, Impressing, Funny...... Quotes


  • Diplomacy is the art of saying "nice doggy" ... until you can find a rock. 
  • It's not a bug, it's a feature. >> Support 
  • As far as I can tell, calling something philosophical is like greasing a pig to make it hard to catch. 
  • It’s always known that one horse can run faster than another. But which one? 
  • Some people will believe anything if you whisper it to them. 
  • If you want to make peace, you don’t talk to your friends. You talk to your enemies. 
  • We could never learn to be brave and patient If there were only joy in the world. 
  • War does not determine who is right - only who is left. 
  • Gratitude is expensive. Revenge is profitable. 
  • A synonym is a word you use when you can’t spell the word you first thought of. 
  • The greatest weariness comes from work not done. 
  • It may be that your whole purpose in life is simply to serve as a warning to others. 
  • Anything is possible, but only a few things actually happen. 
  • No matter how big or soft or warm your bed is, you still have to get out of it. 
  • I went on a diet, swore off drinking and heavy eating, and in fourteen days I lost two weeks. 
  • We make a living by what we get, we make a life by what we give. 
  • I slept, and dreamed that life was beauty;I woke, and found that life was duty. 
Visit http://ganeshtiwaridotcomdotnp.blogspot.com/2011/06/some-intelligent-humorous-quotes-about.html for some intelligent/ humorous quotes

Java Image - read image and separate RGB array values

Reading image and getting values of Red Green Blue and Alpha values in separate 2d arrays :

public class TestImagesss {
    public static void main(String[] args) {
        int value[][]=getRGB(getImage("test.jpg"));
        int valueR[][]=getR(getImage("test.jpg"));
    }
    //.... code below :

maven - pom.xml define properties constants

Define :
    <properties>
        <my_Constant_String>com.gt.App</my_Constant_String>
    </properties>
Use :

 <some_property_tag>${my_Constant_String}</some_property_tag>

screen logger - capture screen periodically and save to folder - java

Screen Capture Logger Java Application : Capture screen in fixed interval and save jpeg image to a folder.
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;

import javax.imageio.ImageIO;

public class ScreenLogger {
    private static final String saveLocation = "c:\\logs\\";
    private static final int timeInterval = 1000 * 30;
    private static Rectangle rect;
    private static Robot robot;

    public static void main(String[] args) throws Exception {
        init();
        new Thread(new CaptureThread()).start();
    }

J2ME Bluetooth discover connect send read message

Bluetooth communication - discover (by both server and client), connect to ad hoc network, send, receive message in J2ME java code.
This working java source code was used in our project  BlueChess- two player chess game over bluetooth adhoc connection
Code:
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.bluetooth.DiscoveryAgent;
import javax.bluetooth.LocalDevice;
import javax.bluetooth.ServiceRecord;
import javax.bluetooth.UUID;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import javax.microedition.io.StreamConnectionNotifier;

public class BtCommunication {

    private StreamConnectionNotifier scn=null;
    private DiscoveryAgent mDiscoveryAgent=null;
    private StreamConnection conn = null;
    private InputStream inputStream=null;

Java:opening a folder in windows explorer

opening a directory using start utility in windows

String cmd = "cmd.exe /c start ";
String file = "c:\\";
Runtime.getRuntime().exec(cmd + file);

Creating DSL / PPPOE Connection in UBUNTU

I have internet connection (worldlink-512kbps, cable net) shared with landowner and flatmates through wireless router. I recently created a PPPOE (Point to Point Protocol Over Ethernet) dial-up connection on my laptop to use whole bandwidth during load-shedding.

Creating DSL connection in Ubuntu is extremely easy.

Create, configure maven project in eclipse - example tutorial

In this post, the followings are covered :
  • Download and Install maven in windows:
  • Add M2_REPO classpath variable in eclipse 
  • Generate Java/Web Project  with maven and import in eclipse
  • Add another dependency from web repository
  • Add custom or 3rd party library manually into repository:
  • Benefits of using MAVEN :