Javascript/CSS Minification With YUI Compressor

'Minification' is a process of compressing the source code, without changing it's functionality. This technique is useful sometimes, specially in the case of a web application with huge Javascript/CSS files. In other cases, it's probably just a micro-optimization. Minifying js/CSS files will reduce the bandwidth used and also improves the performance of the application. As per Wikipedia Source:
Minified source code is especially useful for interpreted languages deployed and transmitted on the Internet (such as JavaScript), because it reduces the amount of data that needs to be transferred. Minified source code may also be used as a kind of obfuscation. In Perl culture, aiming at extremely minified source code is the purpose of the Perl golf game.

Minified source code is also very useful for HTML code. As an example, successive whitespace characters in HTML are rendered as a single space, so replacing all whitespace sequences with single spaces can considerably reduce the size of a page.

There are a couple of tools available to minify js/CSS code, like Google's Closure-Compiler, Yahoo's YUI Compressor, JSMin, etc. If you are using Maven for your build process, you can use the Maven plugin for YUI Compressor, as below:



And the plugin repository, is as below:



I created a sample web application with "js" folder to store javascript files and used the above configuration to test the 'Minification' process. I downloaded the latest version of JQuery (both files - 'Minified' and 'Uncompressed' 1.7.2 version files) and copied it to my "js" folder and built the web application using Maven. The downloaded JQuery files weighed as noted below:
JQuery-1.7.2.js --> 253 KB
JQuery-1.7.2.min.js --> 95 KB

After the Maven Build, the JQuery-1.7.2.js is minified and the minified js file weighed as noted below:
JQuery-1.7.2-min.js --> 108 KB

The above results show that the 'Minification' process is working pretty fine. So, if you are using a lot of javascript/css files in your web application, consider minifying your js/css code, so that you can reduce the data transferred and also improve the performance of your web application. In some cases, it might be a micro-optimization. So, let me also remind you that 'Premature Optimization is the root of all evil'.

Add 'Syntactic Sugar' With 'Fluent Interface'

'Fluent Interface' is a Object Oriented Programming technique for adding more 'Syntactic Sugar' to the language. This just makes the code more 'Readabale' and 'Expressible'...just shows the flow of logic, in a clear way. This term (Fluent Interface) was first coined by Eric Evans and Martin Fowler. One way of achieving this, is to use 'Method Chaining'. In Java or any other Object Oriented programming language, you can achieve this by returning the Object itself (using 'this' keyword), thus allowing the calls to be chained together, in a single statement.

Below is a sample class (CustomList.class, which extends ArrayList):

import java.util.ArrayList;
 
/**
*
* @author Babji, Chetty
*/
public class CustomList extends ArrayList {   
    public CustomList addElem(Object e) {
        super.add(e);
        return this;
    }
}


In the above class, you can see the custom 'addElem' method, which returns the Object itself (this), thus allowing it for 'Method Chaining'. Below is the 'Fluent Interface Demo' class:

import com.chetty.data.CustomList;
import java.util.ArrayList;
 
/**
*
* @author Babji, Chetty
*/
public class FluentInterfaceDemo {
    public static void main(String[] args) {
        ArrayList<String> arrList = new ArrayList<String>();
        
        arrList.add("string1");
        arrList.add("string2");
        arrList.add("string3");
        arrList.add("string4");
       
        CustomList<String> custList = new CustomList<String>();
        
        custList.addElem("string1")
                .addElem("string2")
                .addElem("string3")
                .addElem("string4");               
    }   
}


In the above class, you can see the difference between how you add elements to 'arrList' (ArrayList) and 'custList' (CustonList). That's Syntactic Sugar for you! :)

You can see this kind of implementation, in a couple of Java classes (Like StringBuffer, StringBuilder, BigDecimal, et al). Below is an example of Method Chaining, using Java's BigDecimal:

BigDecimal bigD = BigDecimal.ONE.add(BigDecimal.TEN).multiply(new BigDecimal("5")).divide(BigDecimal.TEN);


And below is an example of using Java's StringBuilder, which shows 'Method Chaining':

StringBuilder sb = new StringBuilder();
sb.append("1")
  .append("2")
  .append("3");


If you look at the Source code for StringBuilder or BigDecimal, the methods used return an Object, thus allowing it to chain. This logic can be applied to any Object Oriented Programming language. If you are familiar with JQuery Javascript Framework, you should be able to figure it out that 'Method Chaining' is extensively used in JQuery. Below is an example:

<div id="divTest1"></div>
<script type="text/javascript">
        $("#divTest1").text("Hello, world!").css("color", "blue");
</script>


Reference: JQuery Method Chaining

There are also a couple of DSL's which are specially built, using this concept of 'Fluent Interface'. Op4j is one interesting framework among 'em. Below is example code for Op4j:

Set<Calendar> set = 
      Op.on(list).toSet().forEach().exec(FnString.toCalendar("dd/MM/yyyy")).get();


Reference: Op4j (You can find more interesting examples in the referenced source).

Priority Queue in Java

'Priority Queue' is a data structure similar to Queue, but pulls/pops out the first element with top priority first (FPIFO, for convenience), whereas Queue is just 'First In First Out' (FIFO). This data structure can be used in a variety of applications like Scheduling, Bandwidth Management, Discrete Event Simulation, etc.

I was just coding for fun and for brushing up my skills on algorithms and coded a few examples, as listed below. As shown in the examples, I used the Java's PriorityQueue implementation in the util package.

In the below example, the priority queue is fed with Integer numbers and the priority is determined by checking if the number is a least prime or not.
import java.util.Comparator;
import java.util.PriorityQueue;

/**
 *
 * @author Babji P, Chetty
 */
public class PQueueTest {
    public static void main(String[] args) {
        PriorityQueue<Integer> pQueue = new PriorityQueue<Integer>(10, new Comparator<Integer>() {

            public int compare(Integer int1, Integer int2) {
                boolean flag1 = isPrime(int1);
                boolean flag2 = isPrime(int2);
                
                if (flag1 == flag2){
                    return int1.compareTo(int2);
                } else if (flag1) {
                    return -1;
                } else if(flag2) {
                    return 1;
                }
                
                return 0;
            }
        });

        pQueue.add(10);
        pQueue.add(8);
        pQueue.add(6);
        pQueue.add(4);
        pQueue.add(2);
        pQueue.add(9);
        pQueue.add(7);
        pQueue.add(5);
        pQueue.add(3);
        pQueue.add(1);

        while(true) {
            Integer head = pQueue.poll();
            if(head == null) {
                break;
            }
            
            System.out.print(head + "  <-- ");
        }
    }
    
    /**
     * 
     * @param n
     * @return 
     */
    public static boolean isPrime(int n) {
        if (n <= 1) {
            return false;
        }
        if (n == 2) {
            return true;
        }
        if (n % 2 == 0) {
            return false;
        }
        long m = (long) Math.sqrt(n);

        for (long i = 3; i  <= m; i += 2) {
            if (n % i == 0) {
                return false;
            }
        }

        return true;
    }
}

The output for the above example is:
2 <-- 3 <-- 5 <-- 7 <-- 1 <-- 4 <-- 6 <-- 8 <-- 9 <-- 10 <--
As you see, prime numbers appear before other numbers.

The below example is more of a real world example, where the order of patients to be treated by a doctor can be determined by checking if it's a emergency case or not.

Below is the code for 'Patient' class:
/**
 *
 * @author Babji P, Chetty
 */
public class Patient {
    private int id;
    private String name;
    private boolean emergencyCase;
    
    public Patient(int id, String name, boolean emergencyCase) {
        this.id = id;
        this.name = name;
        this.emergencyCase = emergencyCase;
    }

    /**
     * @return the id
     */
    public int getId() {
        return id;
    }

    /**
     * @param id the id to set
     */
    public void setId(int id) {
        this.id = id;
    }
    
    /**
     * @return the name
     */
    public String getName() {
        return name;
    }

    /**
     * @param name the name to set
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * @return the emergencyCase
     */
    public boolean isEmergencyCase() {
        return emergencyCase;
    }

    /**
     * @param emergencyCase the emergencyCase to set
     */
    public void setEmergencyCase(boolean emergencyCase) {
        this.emergencyCase = emergencyCase;
    }
}


And below is the code for testing Patient priority queue:

import com.chetty.algos.data.Patient;
import java.util.Comparator;
import java.util.PriorityQueue;

/**
 *
 * @author Babji Prashanth, Chetty
 */
public class PQueueTest {
    public static void main(String[] args) {
        PriorityQueue<Patient> patientQueue = new PriorityQueue<Patient>(10, new Comparator() {
            public int compare(Patient patient1, Patient patient2) {
                return (patient1.isEmergencyCase() == patient2.isEmergencyCase()) ? (Integer.valueOf(patient1.getId()).compareTo(patient2.getId()))
                                                                                  : (patient1.isEmergencyCase() ? -1 : 1);
            }
        });
        
        patientQueue.add(new Patient(1, "Patient1", false));
        patientQueue.add(new Patient(2, "Patient2", false));
        patientQueue.add(new Patient(3, "Patient3", true));
        patientQueue.add(new Patient(4, "Patient4", false));
        patientQueue.add(new Patient(5, "Patient5", true));
        
        System.out.println();
        System.out.print("Doctor's waiting for patients  : ");
        while(true) {
            Patient currentPatient = patientQueue.poll();
            if(currentPatient == null) {
                break;
            }
            
            System.out.print(currentPatient.getName() + " <-- ");
        }
        System.out.println();
    }
}


The output for the above example is:
Doctor's waiting for patients : Patient3 <-- Patient5 <-- Patient1 <-- Patient2 <-- Patient4 <--
As you see, patients who need to be treated immediately (emergency cases) appear before other patients.