Wednesday, July 29, 2015

Best programming practice

Today, I was going through the code of someone and found it difficult for myself to read it. And the reason behind that was too many If's and too many switch cases. Each method was written with more then 30 line of code. I wasn't sure that why he has choose Object Oriented Programming when he had to do that.

Every developer who is willing to improve his programming skills he must need to keep one rule in his mind before writing code:

Someone will read your code someday

I think few just leave their code without method level or class level comments; so that no one get to know that who wrote that code. But, those stupids forget that subversion do this too.

Anyway few of the things I think should be simple in code:


  1. Class level comments
  2. Method level comments
  3. Method should be well-commented
  4. Atomic
  5. NO to Conditional Programming
I am not going to debate on comments because you can get this information from a lot of blogs. So, I will start this blog from the 4th Point:

Atomic:

Forget it that you will get 100+ methods in class or not. But, try to keep every single method for one task not for more then one task.

Example
public void calculateAndPrint(int i, int j){
    System.out.print(i+j);
    System.out.print(i/j);
    System.out.print(i*j);
    System.out.print(i-j);
}
Correct Way:
public void printSum(int i, int j){
    System.out.println(i+j);
}
public void printMultiply(int i, int j){
    System.out.println(i*j);
}
public void printDivide(int i, int j){
    System.out.println(i/j);
}
public void printSubtract(int i, int j){
    System.out.println(i-j);
}
Don't jump into OOP for the above example as it's just an example and I know it could be implemented well with OOP.

NO to Conditionals Programming

The worst scenario comes when someone try to put his brain in coding. And a big web of If-else or switch-case comes into the code:


An example where someone is trying to handle the SOAP response:
if(eventType == XmlPullParser.START_TAG) {
            soapResponse= xpp.getName().toString();

            if (soapResponse.equals("EditorialOffice")){  
                eventType = xpp.next();
                if (xpp.getText()!=null){
                editorialOffice += xpp.getText();
                }
            }   
            else if (soapResponse.equals("EditorialBoard")){  
                eventType = xpp.next();
                if (xpp.getText()!=null){
                editorialBoard += xpp.getText();
                }
            }
            else if (soapResponse.equals("AdvisoryBoard")){  
                eventType = xpp.next();
                if (xpp.getText()!=null){
                advisoryBoard += xpp.getText();
                }
            }   
        }
        eventType = xpp.next();
     }
Instead of doing above tricky code which is difficult to read could be done in a better way by simply implementing Strategy Pattern:

// Interface
public interface IResponseHandler {
   public void handleResponse(XmlPullParser xxp);

}

// Concrete class for EditorialOffice response
private class EditorialOfficeHandler implements IResponseHandler {
   public void handleResponse(XmlPullParser xxp) {
       // Do something to handle Editorial Office response
   }
}

// Concrete class for EditorialBoard response
private class EditorialBoardHandler implements IResponseHandler {
   public void handleResponse(XmlPullParser xxp) {
       // Do something to handle Editorial Board response
   }
}
// Concrete class for AdvisoryBoard response
private class AdivsoryBoardHandler implements IResponseHandler {
   public void handleResponse(XmlPullParser xxp) {
       // Do something to handle Advisory Board response
   }
}
At a place in your code create something like this

Map<String, IResponseHandler> strategyHandlers = new HashMap<String,IResponseHandler>();
strategyHandlers.put("EditorialOffice", new EditorialOfficeHandler());
strategyHandlers.put("EditorialBoard", new EditorialBoardHandler());
strategyHandlers.put("AdivsoryBoard", new AdvisoryBoardHandler());

And when you get the response just call the handler to do the rest of the things for you:

ResponseHandler responseHandler = strategyHandlers.get(soapResponse);
responseHandler.HandleResponse(xxp);

I hope it will be helpful for the java programmers of 1-3 years of experience.  

MySQL- Hierarchical Data

No developer ever came into the problem of storing hierarchical data. And we always come up with a solution that store the parentId into the same table. And when we just need to retrieve the data then it becomes a nightmare to optimize the nested-join. The advantage to these systems is that they don't take a lot of space, but the disadvantage is that nearly all the maintenance has to be done in the application. So, in essence, these approaches trade lots of queries at retrieval time, for lots of queries at update and insert/delete time, and often some additional programming complexity.

Just imagine a tree and what outcome a user may want:
root
- son
- son#2
- grandson#1
- super grandson
- son#3
-grandson#2

and I want to display it like:

root -> son
root -> son#2
root -> son#2 -> grandson#1
root -> son#2 -> grandson#1 -> super grandson
root -> son#3
root -> son#3 -> grandson#2

In order to get the following output we apply the approach of closure table. A closure table gives you the ability to do all the same sorts of "find me all children of X, to depth N" queries as any of the other methods, just by doing a join against the closure table. And, the killer feature of the closure table, is that to add or remove a parent-child relationship, you only need to run *one* SQL query -- a query so simple that even the least-powerful SQL databases can be configured to run it as a trigger on the main table!

The Closure Table is a design for representing trees in a relational database by storing all the paths between tree nodes.


create table family (
relation_id int auto_increment primary key,
relation varchar(20) not null
);

insert into family (relation_id, relation) values
(1, 'root'),
(2, 'son'),
(3, 'son#2'),
(4, 'grandson#1'),
(5, 'super grandson'),
(6, 'son#3'),
(7, 'grandson#2');

create table family_tree (
ancestor int not null,
descendant int not null,
primary key (ancestor, descendant),
foreign key (ancestor) references family(relation_id),
foreign key (descendant) references family(relation_id)
);

insert into family_tree (ancestor, descendant) values
(1,1), (1,2), (1,3), (1,4), (1,5), (1,6), (1,7),
(2,2),
(3,3), (3,4), (3,5),
(4,4), (4,5),
(5,5),
(6,6), (6,7),
(7,7);


What we need to do is find all the descendants of the root node 1, then for each of these descendant, list its ancestors in order, separated by an arrow. We can use MySQL's useful GROUP_CONCAT() function to build this list for us.

select group_concat(f.relation order by f.relation_id separator ' -> ') as path
from family_tree d
join family_tree a on (a.descendant = d.descendant)
join family f on (f.relation_id = a.ancestor)
where d.ancestor = 1 and d.descendant != d.ancestor
group by d.descendant;

Here's the output in the MySQL client. It looks like what the reader asked for:

+----------------------------------------------------------+
| path                                                                       |
+----------------------------------------------------------+
|root -> son                                                              |
|root -> son#2                                                          |
|root -> son#2 -> grandson#1                                  |
|root -> son#2 -> grandson#1 -> super grandson    |
|root -> son#3                                                          |
|root -> son#3 -> grandson#2                                  |
+----------------------------------------------------------+

I do assume for the purposes of ordering that all of a node's ancestors have a lower node number. You could alternatively use a pathlength column to the family_tree table and sort by that.

The Closure Table design is nice compared to the Nested Sets (or Preorder Traversal) design, because it supports the use of referential integrity. By using indexes, the EXPLAIN report shows that MySQL query optimizer does a pretty good job on it:
MySQL Query Stats


Sunday, July 26, 2015

Java 8 - Lambda & Functional Interfaces

Java 8 supposted to be a major release after Java 5 and it brought a lot of new changes and ease for java developers i.e. language,compiler,libraries,tools and runtime (JVM)

Lambdas and Functional Interfaces
Lambdas allow us to treat functionality as a method argument (passing functions around), or treat a code as data. So, this is must be good news for functional developers and from now on no need for anonymous classes in order to do functional programming with java.

Examples (-> lambda):
  1. Arrays.asList(“a”,”b”,”c”,”d”).forEach( e -> System.out.println( e ) );
  2. Arrays.asList(“a”,”b”,”c”,”d”).forEach( ( String str ) -> System.out.println( str ) );
  3. Arrays.asList(“a”,”b”,”c”,”d”).forEach( ( String str ) -> {
        System.out.println( str ) ;
        System.out.println( str + ”,”) ;
    } );
Obviously lambda expression returns a value to but, it must not need to be declared, if not required.
  1. Arrays.asList(“a”,”b”,”c”,”d”).sort( ( e1, e2 ) -> e1.compareTo( e2 ) );
OR
  1. Arrays.asList(“a”,”b”,”c”,”d”).sort( ( e1, e2 ) ->
    {
        int result = e1.compareTo( e2 );
        return result;
    });

Interface’s Default and Static Methods

Two new concepts of methods in interface; default and static methods.
Default method, make interfaces somewhat similar to traits but serve a bit different goal. They allow adding new methods to existing interfaces without breaking the binary compatibility with the code written for older versions of those interfaces.
The difference between default methods and abstract methods is that abstract methods are required to be implemented.

Example:
private interface Defaultable{
    // Interfaces now allow default methods, the implementer may or
    // may not implement (override) them.
    default String notRequired(){
        return “Default Implementation”;
    }
}
private static class DefaultableImpl implements Defaultable{
}
private static class OverridableImpl implements Defaultable{
   @Override
    public static String notRequired(){
         return “New Implementation”;
    }
}


In java 8 interface can declare and implement static methods too:

private interface DefaultableFactory{
    //a new static method’s
    static Defaultable create(Supplier<Defaultable> supplier){
         return supplier.get();
    }
}
The small code snippet below glues together the default methods and static methods from the examples above.

public static void main(String[] args){
       Defaultable defaultable = DefaultableFactory.create(DefaulatableImpl::new);
       System.out.print(defaultable.notRequired());
       defaultable = DefaultableFactory.create( OverridableImpl::new);
       System.out.print(defaultable.notRequired());
}


Default methods implementation on JVM is very efficient and is supported by the byte code instructions for method invocation. Default methods allowed existing Java interfaces to evolve without breaking the compilation process. The good examples are
java.util.Collection interface:stream(),parallelStream(),forEach() and etc.