Skip to main content


Showing posts from 2012

Google Guice: Dependency Injection with Guice 3.0

Guice (pronounced 'juice') is a lightweight dependency injection framework for Java 5 and above, from Google.

Why Google Guice?
Mature Framework – Used in many open source projects like apache struts, apache shindigetc. Google is using it in many mission critical applications. Simple and easy to use – It help in design better application. JSR 330 supportAOP support Very light weight – less then 1 MB in size Won the 18th Jolt Award  - for best Library, Framework, or Component.
Google Guice with example
Lets consider very high level application design where need services, persistence layer and authentication mechanism. Each of the functionality is very different but very dependent on each other. If we start writing the code without giving much thought on design, then we will be ending with the code, which is very tightly couple, hard to change and even harder to test.

Application design
Application main class
public class Application { private final AppService service; private f…

JavaScript: underscorejs with examples

In previous post I have mention about underscorejs library. And here is the another post to explain bit more about this library.

Some functions used in below example to improve readability 
function prop(name){ return function(obj){ return obj[name]; } } function compareProp(prop, contextProp){ return function(obj){ return obj[prop] === this[contextProp]; } }
Find visible user and show it’s default view
Below is the list of JSON array with user object data. Now we want to show all visible user with it’s default view. var ar = [{ name: 'moe', age: 40, display: true, defaultView: 1, views: [ { name: 'Admin', id: 1 }, { name: 'Role1', id: 2 }, { name: 'Role2', id: 3 } ]},{ name: 'larry', age: 50, display: false, defaultView: 1, views: [ { name: 'Admin', id: 1 }, { name: 'Role1', id: 2 }, { name: 'Role2', id: 3 } ]},{ name: 'curly', age: 60, display: true, defaultVie…

Don’t reinvent the wheel: Some useful JS libraries

It is very common to see “Utility” file in many project, which have all commonly used functions. In other word you can say it is kitchen sink file, where people dump all common functions. Before you realize it grows more than 1000 lines and become a maintenance hell. So keep in mind, each time when you write a new class or function you are increasing the project maintenance coast. There are few things you should consider before writing the code Know Your Library – Most of the library has some utility functions so keep exploring it. Use Utility Library – If existing library doesn't have needed functionality then always consider using 3rd party Utility Library with good test converge.Some of my favourite libraries Underscore JSIt is one of the best utility library, which has collection of most commonly used functions. Here are few function with example code. Each_.each([1, 2, 3], function(num){ alert(num); }); => alerts each number in turn... _.each({one : 1, two : 2, three …

BOM Character: Unknown guest in your file

Many times I have seen special character like “  ” in starting of file and most of the time I ignored it. But recently it started causing more trouble, when my JS validation utility started failing. And log file shows same special character again. After more investigation, I find out it was introduce when I creates a new file in Eclipse.

So, what is this symbol?

It is a BOM (byte order mark) character used to signal the endianness (byte order) of a text file or stream[wiki]. This character differ based on encoding type like

Encoding Symbol UTF-8UTF-16 (BE)þÿUTF-16 (LE)ÿþ
Next question is, how to remove this character from my file. And if you are using Notepad++ editor it will be much easier. You have to select the “Encoding” option from menu bar and choose “Convert to UTF-8 without BOM”.

How to handle BOM character in your code?

I will suggest to use some sophisticated library instead of rolling out your own solution. And “Apache Commons IO” library has dedicated class “BOMInputStr…

“80–20 rule” in Software - Some Interesting facts

80-20 rule states that, for many events, roughly 80% of the effects come from 20% of the causes. In Software Development80% of users only require 20% of the features 80% features are done in 20% of project time (requirement added to the project very late) 80% of requirement conceptualized by everyone within 20% time of first meeting I really like the iterative development which help to overcome from these facts because it break big cycle of project development to small feature development cycle, where we can prioritise the feature based on 80% users and start development. It is only successful when features are done within the iteration, and I really mean done (*agile methodology has done-done concept and that is very useful) And just want to remind another agile practice known as Jamboree meetings for project planning to overcome from last point. Actually I am quite fond of agile practices =) In software Quality20% top most reported bugs fixes, will eliminate 80% of the applica…

Java: Singleton class - double-checked locking

Most of the singleton class implementation i have seen are inefficient or buggy specially in multithreaded environment. So, here is my two cents on singleton classes.
We can implement singleton class based on 
Eager instantiation and Lazy instantiation
Singleton class based on eager instantiation
In “Effective Java” Josh Bloch preferred using single element enum type to implement singleton class.

public enum Singleton { ISTANCE; //other methods }
Singleton class based on lazy instantiation
Some developer use synchronized method to make method thread safe but it make your function very slow. Other way to make function thread safe is synchronized block. But incorrect use of it, will result in same performance bottleneck.
Here is the preferred way to make singleton class thread safe. (“double-checked locking” algorithm).

public class Singleton { private static volatile Singleton INSTANCE = null; private Singleton(){} public static Singleton getInstance(){ Singleton inst = INSTA…

Java: Strong References, Soft References and Weak References

There are many use-cases where we want to control, when our objects are collected by GC(Garbage Collector). Package "java.lang.ref" provides reference-object classes, which support a limited degree of interaction with the garbage collector. And GC reclaim the object memory based on it's reachability.

Strong Reference Newly created objects are strongly reachable by the thread that created it. So object will be remain in heap till thread is running or some variable hold this object reference.

//leaking array private static List<String> leakingArrayWithStrongRef = new LinkedList<String>(); public void StrongReferenceTest(){ try { for (int i = 0; i < 500000; i++) { String data = LEAKING_DATA + i; // Add data to our leaking array... leakingArrayWithStrongRef.add(data); } } catch (OutOfMemoryError ofm) { System.out.println(&quo…

JMeter: Creating First Load Test

What we want to do Simulate concurrent users Simulate requests Generate reports Troubleshooting
JMeter GUI Test Pan Plan is a root element where all test related settings are define. In Thread Group we can define pool of user to simulate load on the test Work Bench is for non test helpers
Common terms in JMeter User           ⇒ Thread Request     ⇒ Sampler Report       ⇒ Listeners
Setting up the load test 1. Simulate concurrent users Add thread > Thread Group Number of Threads - concurrent users =10 Ramp-Up Period - seconds until all users are active =1 (eg. if user define 10 Threads and 100 Ramp-Up Period then, it means each thread will start in 100/10=10 seconds time difference) Loop Count - how many repetitions =1 Calculating think time
                                     Ramp-up time                 = 120 seconds
                                     Number of users             =  30
                                     Then think time will be  =  ramp up time/number of users  …

Guava: Some useful IO utilities

Guava IO package provides very useful utility classes for input/ouput stream, byte stream, file handling and many more. Here are few example which show case how these utilities can make your code much cleaner, modular and more readable.Copy “InputStream” to “OutputStream InputStream is = CopyStreams.class.getResourceAsStream("test.txt"); OutputStream os = System.out; ByteStreams.copy(is, os);Changing InputStream to “byte[]” InputStream is = CopyStreams.class.getResourceAsStream("test.txt"); byte[] isBytes = ByteStreams.toByteArray(is); // Now if you want to get base64 encoded string then it will be like this String isBase64Str = new sun.misc.BASE64Encoder().encode(isBytes);Combining two files in one File input1 = new File("c:\\testio\\AWords.txt"); File input2 = new File("c:\\testio\\BWords.txt"); File output = new File("c:\\testio\\ABWords.txt"); …

JavaScript [ExtJs3]: Total “Record” count in filtered store

There is two way to get record count from the Store
store.getTotalCount() This function depend on server response value. For accuracy of the value, property shell if return by the server.

Property name for the diff. reader:
totalProperty for JsonReader, totalRecords for XmlReaderstore.getCount() Will return you the number of record from the store.
Or if you have filter on the store, it will give you the number of filtered record.
But if you want to get the total number of record regardless filtering, Then it will be like this

var totalRecords = store.snapshot ? store.snapshot.length : store.getCount();
“snapshot” is the variable in “Store” which hold the actual data in case if you have applied a filter.

JavaScript: Experimenting with Conditional Statement

When conditional statement in your application grow to 30 lines or more, then it’s time for code refactoring. Conditional statements are un-avoidable but JavaScript functional programming behavior gives you really good way to handle such kind of scenario. 

Just take a scenario where you have to write a function which return sound for the given animal.

var soundOf = function(animal){ var sound; if(animal === 'dog'){ sound = 'bark'; } else if(animal === 'duck'){ sound = 'quack quack'; } else if(animal === 'owl'){ sound = 'hoot'; } else { sound = 'animal not found!!!'; } return sound; }
Now think, what your code look like when you have to support 100 animal !!!
And same will be true for switch-case statement

var soundOf = function(animal){ var sound; switch(animal){ case 'dog': sound = 'bark'; break; case 'duck': sound = 'quack quack'; break; case 'owl&…

JavaScript Design Patterns

Guava: ClassToInstanceMap

If you have requirement of associating the class to an instance of it’s type then ClassToInstanceMap is the best choice for you. It comes with additional type safety.

It’s an extended interface of Map

public interface ClassToInstanceMap<B> extends Map<Class<? extends B>,B>
ImmutableClassToInstanceMap, MutableClassToInstanceMap
Here is a example where you can use this map
Some classes 

interface Writer{ //SOME CODE } class TemplateWriter implements Writer{ //SOME CODE } class PropertyWriter implements Writer{ //SOME CODE } class PropertySetWriter implements Writer{ //SOME CODE }
And we have one Factory class

class WriterFactory{ private static final ClassToInstanceMap<Writer> factoryMap = new ImmutableClassToInstanceMap.Builder<Writer>(). put(TemplateWriter.class, new TemplateWriter()). put(PropertyWriter.class, new PropertyWriter()). put(PropertySetWriter.class, new PropertySetWriter()). build(); public static Wr…