Friday, September 20

Java Reflection API , Refection advantages in java , Java Refection introspection basics.

Java Reflection API , Refection advantages in java , Java Refection introspection basics.




                                                                  Java Refection API

Refection is useful where to don't want to write a logic repeatedly many times for similar kind of object structure creation .

Reflection will reduce the overall code drastically and help in maintaining a generic code for multiple modules.

Refection directly operates on java meta data , Meta data of class like class name , constructor , methods , variable and thus provide a generic way of writing logic for multiple similar object structures

Refection provide you capability of introspecting and invoking operations by searching the suitable method at run-time.

For Example :

public class JavaReflection{


public static void PrintClassDetailsObject obj)

 Class type = obj.getClass();
 final Method[] methods = type.getMethods();

if(type instanceOf Politician)
foreach (Method method: methods )
if(method.equalsIgnorecase(ContentElection)

method();

)

if(type instanceOf Doctor
foreach (Method method: methods )
if(method.equalsIgnorecaseoperatePatient

method();

)

if(type instanceOf Actor
foreach (Method method: methods )
if(method.equalsIgnorecase(playRole)

method();

)
}
As illustrated in above example at run-time It is being identified which class does the object belongs to and depending upon that a specific method is searched out. If method is available then required operation is performed. There are lot of If ,else conditions but good thing is that we are not writing there different classes to handle different sent of features .


So if there are 1000 variations of the above implementation all can be easily plugged in here .So you are writing little code catering to wide range of features and introducing generic behavior which further makes it extensible with very little extra code and effort As the basic structure and design for any similar enhancement is already in place. No further investment of design for enhancement of similar nature But Just the core implementation effort. 

Refection class here is creating an execution blueprint . It does not have feature specific logic or code But in certain cases this kind of implementation is useful when we want to provide a centralized control of routing the request to different classes.



Reflection also has got the capability of handling overloaded methods. At run-time we can check parameters passed along with the method name to resolve the exact method .

For example :

 for (int idx = 0; idx < methods.length; idx++) {
     if (methods[idx].getName() .startsWith"PLAY"{
 if (methods[idx].getParameterTypes()[0] == String.class) {
 methods[idx].invoke(obj, new Object[] { new String() }
);
}}










Top 3 most used classes of Refection API in java


1. Class java.lang.reflect.Method

 
This class contains a description of a method and the means to dynamically invoke
it. You can use instances of this class to dynamically invoke methods.


2. Class java.lang.reflect.Modifier


  Using Modifier , you can determine whether a field is public,private,static,transient , and so on.

3. Class java.lang.reflect.AccessibleObject

 It allows you to bypass class access constraints such as “private,” which allows you to
execute methods and set fields that would normally be blocked by visibility specifiers. Visibility of private fields can be modified to make it accessible at run-time.





Thursday, September 19

java composite design pattern , OO design pattern , composite tree design

              java composite design pattern , OO design pattern , composite tree design

-->


                                                           Composite Design Pattern

Composite design pattern is based on creating a tree structure in such a way that an individual leaf of the tree can be treated just like entire tree composition. Means all constituents of the tree consist of similar properties and can be represented with single interface.

 

For Example :

public interface Employee{

     public void addEmployee(Employee employee); 
     public void removeEmployee(Employee employee); 
     public Employee getEmployeeChild(int i); 
     public String getEmployeeName(); 
     public double getEmployeeSalary(); 
   
}




    public class Manager implements Employee{ 
     
     private String name; 
     private double salary; 
     
     public Manager(String name ,double salary){ 
      this.name = name; 
      this.salary = salary; 
     } 
      
     List employees = new ArrayList(); 
     public void add(Employee employee) { 
        employees.add(employee); 
     } 
     
     public Employee getChild(int i) { 
      return employees.get(i); 
     } 
     
     public String getName() { 
      return name; 
     } 
     
     public double getSalary() { 
      return salary; 
     } 
     
      public void remove(Employee employee) { 
      employees.remove(employee); 
     } 
     
    } 



    public class Developer implements Employee{ 
     
        private String name; 
        private double salary; 
     
        public Developer(String name,double salary){ 
            this.name = name; 
            this.salary = salary; 
        } 
        public void add(Employee employee) { 
            //this is leaf node so this method is not applicable to this class. 
        } 
     
        public Employee getChild(int i) { 
            //this is leaf node so this method is not applicable to this class. 
            return null; 
        } 
     
        public String getName() { 
            return name; 
        } 
     
        public double getSalary() { 
            return salary; 
        } 
     
      
        public void remove(Employee employee) { 
            //this is leaf node so this method is not applicable to this class. 
        } 
     
    } 



-->






public class CompositeDesignPatternMain { 
 
 public static void main(String[] args) { 
  Employee emp1=new Developer("John", 10000); 
  Employee emp2=new Developer("David", 15000); 
  Employee manager1=new Manager("Daniel",25000); 
  manager1.add(emp1); 
  manager1.add(emp2); 
  Employee emp3=new Developer("Michael", 20000); 
  Manager generalManager=new Manager("Mark", 50000); 
  generalManager.add(emp3); 
  generalManager.add(manager1); 
  generalManager.print(); 
 




Have a look at CompositeDesignPatternMain class carefully. Here using same interface Employee we are able to create a developer , manager and entire tree structure . In tree structure at top there is manager and below that that manager developers are added.

Similarly in other instance GeneralManager is at the top in the tree and manager and developer are added under it. Point to notice is that all tree structure and every individual leaf is being created using same interface . So the combination of Employee ,Developer,Manager is written is such a way  that reference Employee is sufficient to create a leaf of tree as well as entire structure . So here objects are composed in such a way that a single Employee reference can represent entire tree structure as well as single leaf of manager or developer or even any part of the tree .

Thus composition design pattern basically facilitate the concept of identifying commonality and designing various components around base structure in such a way that Base interface can suffice all leaf's requirement as well as can represent the entire tree structure.







-->


String concatenation trimming ,String immutability ,java String and memory management

String concatenation trimming ,String immutability ,java String and memory management





String s="hello";

This created an oject in memory

Object = "hello"    Reference =s

s+="World "

This creates a new object in memory

Object ="hellow world "  reference =s

Now in total , there are two objects in memory

 Object ="hellow world"  reference =s
Object = "hello"    Reference = none (no reference of "hello" object available)


s.trim();

What happens here?

A new object is created.

So now there are three objects memory

"hello"
"hello world "
"hello world"

and only "hello world " has a reference to it.






Strings are immutable objects. So once created can't be modified . On modification Java creates another String instance in memory. String pool maintains all string values at single place and If same oject is created multiple times java does not create multiple objects in memory but add reference to existing object. Thus an String can have multiple references in Java.










Wednesday, September 18

Apache Hadoop and Mumbai dabbawala .. Apache Hadoop is in practice for more than 100 years..

Apache Hadoop and Mumbai dabbawala .. Apache Hadoop is in practice for more than 100 years..
-->




  • Just like HDFS slices and distributes the chunk of data to individual nodes, each household submits the lunchbox to a Dabbawala.
  • All the lunchboxes are collected at the common place for tagging them and to put them into carriages with unique codes. This is the job of the Mapper!
  • Based on the code, carriages that need to go to the common destination are sorted and on-boarded to the respective trains. This is called Shuffle and Sort phase in MapReduce.
  • At each railway station, the Dabbawala picks up the carriage and delivers each box in that to respective customers. This is the Reduce phase.
Just like the way each node in the cluster does its job without the knowledge of other processes, each Dabbawala participates in the workflow just by focusing on his task. This an evidence of how a parallelized environment can scale better.



-->





-->

OO design principals and fundamentals , Java design principals





Rigidity

Tendency to change is very difficult. Any change will trigger many cascading change. Software modules are tightly coupled So very little flexibility.


Fragility

Tendency to break easily. Any change can trigger a lot of defects in lot of features. Creates unexpected problems . Hard to regress and write a proper test plan . Hard to cover all unit test cases. Bad design


Immobility

Movement is very hard. It requires lot of effort in moving a part of software from one section to other . Refactoring is not easy . A part of system that could be useful somewhere else could not be moved.







Viscosity

A system where doing right things is easy. Smallest change can trigger huge risk. When system becomes more dependent on hacks than actual design refinement Its viscosity is high . When System starts performing poorly and developers have no clue Where is the issue and they are forced to try and apply dangerous quick fixes and workarounds , Viscosity is high

Needless repetition

DRY design principal says Do Not repeat. Repetition makes a code difficult to manage and maintain . Software should be designed in a way that code repetition is avoided.


Opacity

A code having so particular pattern . Tough to understand . Very tough to read it .


SOLID design principals

SRS - single responsibility principal . A class or interface should take care of only one feature and should not mix many. For multiple features multiple classes/interface should be written. If a class has to be changed there should be only one reason of change. Class should never have multiple responsibilities

OPEN CLOSED Principal : A software should be open to extension but closed to modification. Behavior of class ,method ,interface should be extensible but should be available for internal modification. Abstraction is the way to apply this . Subclass of abstract class should be free to extend the features of abstract class But should be restricted to modify existing method or behavior.

LSP -Liskov substitution principal : A variable expected as argument in method should be replaceable by sub class of the argument type.

ISP - Interface segregation principal . Interfaces should be segregated intelligently and should not contain methods related to multiple features . Interface should be written in such a way that tit does not force any of it's client to implement a method forcefully .

DIP - dependency inversion principal . Basically push approach instead of Pull. Instead of a client ask for it's dependencies , those dependencies are plugged in in to the objects at the time of instantiation. Abstraction should not depend upon details instead details should depend upon abstraction