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.

Saturday, August 30, 2014

How to solve Gradle project sync failed error in Android Studio

Before Android Studio I was using MotoDev an android IDE by Motorola. But, I found Android Studio which was developed on IDEA. Whenever we create a new project using Android Studio it develops on Gradle. A very common problem with Gradle that if we don't have internet then it fails building your project and gives an exception:

 Gradle project sync failed error
This error caused because it always try to find libraries over Internet and when it fails to find the dependencies then it fails. So, in order to execute you project offline you must need to fix this project setup.


  • Click on Invalidate Caches/Restart from the File Menu



  • Click on Invalidate and Restart



  • Let it download all the Gradle stuff it needs once, Gradle build success !
  • Rebuild project. After successful build of the project you may able to build your project offline.

Wednesday, August 27, 2014

Read Multiple Rows from Android SQLite Helper

This blog is in continuity with my previous three posts which were related to creation of a database helper class, insertion of new data entry intothe table and selection of a record from the database. After creating database in android and open the connection we had to add entries into the database. And after that we have seen how to select a single record from the database.

But now it's time to move to more advance level of retrieving records from the table. And now we must need to select multiple records from the table and populate it to the collection of POJO. (PreferenceInfo.java)

In order to retrieve a stored record into database we had to provide an identity value which will search the record into table against that id. But, here we are planning to search all the records from the database.

A List is a collection which maintains an ordering for its elements. Every element in the List has an index. Each element can thus be accessed by its index, with the first index being zero. Normally, Lists allow duplicate elements, as compared to Sets, where elements have to be unique.
public List<PreferenceInfo> getAllUsers(){
List<PreferenceInfo> preferenceInfos = new ArrayList<PreferenceInfo>();

This time query must not contain any kind of selection criteria and should remain wild.
String query = "select * from " + REGISTER_TABLE;

Now, we must need a connection in order to execute this query. This time we are planning to executing a raw query so will need a Writable Database object.
SQLiteDatabase db = this.getWritableDatabase();

Here, we must need to store the results into the Cursor so that we can retrieve every single row and assign it to the POJO. Once things will be done we will start adding it to the list after each row population.
Cursor cursor = db.rawQuery(query, null);

Iterating over each row, building POJO and adding it to list
PreferenceInfo prefInfo = null;

Move the cursor to the first row. This method will return false if the cursor is empty.
if(cursor.moveToFirst()){
do{

Refreshing object in each iteration and assigning new values from the cursor.
prefInfo = new PreferenceInfo();
prefInfo.setSecurityNumber(Integer.parseInt(cursor.getString(0)));
prefInfo.setEmail(cursor.getString(1));
prefInfo.setPassword(cursor.getString(2));
prefInfo.setUserName(cursor.getString(3));
prefInfo.setMobileNumber(cursor.getString(4));
prefInfo.setKeyMessage(cursor.getString(5));

Adding each object to the list
preferenceInfos.add(prefInfo);
}while(cursor.moveToNext());

Move the cursor to the first row. This method will return false if the cursor is empty. And after completion of iteration we will simply return the list to the method.


  return preferenceInfos;

If you find it helpful kindly click the donate button on the top of page. Also added an attachment of the files used in this blog which can bee seen by clicking on links below:

Read One Record from SQLite Android Helper

This blog is in continuity with my previous two posts which was related to creation of a database helper class and insertion of new data entry into the table. After creating database in android and open the connection we had to add entries into the database. But, as we are already done with the insertion of records into the table. So, now it's time to search for the added record.

So, here we will use PreferenceInfo POJO for assigning retrieved values to the object.

in order to retrieve a stored record into database we must need to provide an identity value which will search the record into table against that id.
public PreferenceInfo getUser(int id){

As I have already mentioned in my previous two blogs; we must need to get a readabledatabase object because here we only need to read a database.

SQLiteDatabase db=null;
// 1. get reference to readable DB
try{
db = this.getReadableDatabase();
}catch (Exception e){
Toast.makeText(currentContext, "database cannot be opened", Toast.LENGTH_LONG);
}

Now like the database we must need to initialize the cursor. Cursor interface provides random read-write access to the result set returned by a database query. So, now we must need to build query:
Cursor cursor =
db.query(REGISTER_TABLE, // a. table
COLUMNS, // b. column names
SECURITY_NUMBER +" = ?", // c. selections
new String[] { String.valueOf(id) }, // d. selections args
null, // e. group by
null, // f. having
null, // g. order by
null); // h. limit

Now, we must need to check for the cursor, if results will be returned then cursor will be populated else it will remain null.
if (cursor != null)

after validating the cursor, we must need to move the cursor to the first row. This method will return false if the cursor is empty. Here, we are retrieving only one record because we know that for each identity only one record exist into the table.
cursor.moveToFirst();

Now we must need to populate the data from table into the POJO and then return the object into that method.
PreferenceInfo preferenceInfo = new PreferenceInfo();

Now we will get the values from the zero-based index of the target column and will set into the relevant property of POJO using the setters.
preferenceInfo.setSecurityNumber(Integer.parseInt(cursor.getString(0)));
preferenceInfo.setEmail(cursor.getString(1));
preferenceInfo.setPassword(cursor.getString(2));
preferenceInfo.setUserName(cursor.getString(3));
preferenceInfo.setMobileNumber(cursor.getString(4));
preferenceInfo.setKeyMessage(cursor.getString(5));

After complete transformation of cursor to object, we will return the object back to the method.
return preferenceInfo;


If you find it helpful kindly click the donate button on the top of page. Also added an attachment of the files


Now, the updated DatabaseHelper file and PreferenceInfo.java file

Insert new record into SQLite Database Android


This blog is in continuity with my previous post which was related to creation of a database helper class. After creating database in android and open the connection we need to add entries into the database.

But before that we just need to create a POJO (Plain Old Java Object) for the table so that we can store the values and directly send it to the database. POJO of PreferenceInfo can be downloaded from this link. (PreferenceInfo.java)

In order to add a new entry into the database we get a SQLiteDatabase writable instance by adding following line
SQLiteDatabase db = this.getWritableDatabase();

After getting the database we must need to set the values that we need to persist into the database to sepecific column name:
ContentValues newValues = new ContentValues();
newValues.put(E_MAIL, preferenceInfo.getEmail());
newValues.put(PASSWORD, preferenceInfo.getPassword());
newValues.put(USER_NAME, preferenceInfo.getUserName());
newValues.put(MOBILE_NUMBER, preferenceInfo.getMobileNumber());
newValues.put(KEY_MESSAGE, preferenceInfo.getKeyMessage());

Now, insert the values into the table by using insert method of the SQLiteDatabase instance
db.insert(REGISTER_TABLE, //table
null,//ColumnHack,
newValues); // key/value -> keys = column names/ values = column values

Now after each and everything we must need to close the database connection after adding the data into database.
db.close();


Updated AndroidHelper file and PreferenceInfo.java POJO.