Month: January 2013

Builder Pattern For Complex Validations

Builder Pattern For Complex Validations

So, here is an extensible API for complex validations. I’ve written a small piece of code for common validations. The code can be extended to introduce more complex validations. Highlights – Builder Pattern Extensible code Non-instantiable Validation class Used a variety of concepts I discussed in the past month Here is the link to the …

+ Read More

Item 12: Consider implementing comparable

Item 12: Consider implementing comparable

Usually while thinking of real time examples for a code solution, one often ends up comparing two objects. e.g. listing the companies in IT in the reverse order of their turnovers. This needs some comparison between 2 instances of object say TurnOver. Enough for the intro, the title tells you where exactly I am heading. …

+ Read More

Item 11: Override clone judiously

Item 11: Override clone judiously

Before talking on the clone method in java, I must list some very important facts. Object class has a clone method, but it is protected. So, it is not available to our objects.  One can always override the clone method, but you will get CloneNotSupportedException unless you make the class implement Cloneable interface and implement …

+ Read More

Item 10: Always override toString

Item 10: Always override toString

Providing a good toString makes your class pleasant to use. Not only the users of your class will love using the toString method, even the debuggers IDEs use the toString method of your object. e.g. Which would you rather see when printing a map, “{Jenny=PhoneNumber@163b91}” or “{Jenny=(707) 867-5309}” When practical, the toString method should return …

+ Read More

Item 7: Avoid finalizers

Item 7: Avoid finalizers

There is no guarantee that the finalize method will be called immediately. So, one should not depend upon it for anything time critical. The Great Ancient Myth System.gc and System.runFinalization call finalizers with guarantee. The Truth They even don’t guarantee it, they might increase the probability of execution of the garbage collector The evil siblings …

+ Read More

Item 6: Eliminate obsolete object references

Item 6: Eliminate obsolete object references

Please take a minute to go through the code given below. /** * Example of a memory leak * * @author lekhak.tumblr.com */ public class Stack { private Object[] elements; private int size = 0; private static final int DEFAULT_INITIAL_CAPACITY = 16; public Stack() { elements = new Object[DEFAULT_INITIAL_CAPACITY]; } public void push(Object e) { …

+ Read More

Varargs in main method

Varargs in main method

While going through some of the examples on the internet on “varargs”(variable arguements) feature introduced in Java 1.5, I noticed a strange fact.  No one uses varargs in main method. I fail to think of a reason why. In case you know why, please let me know. What the hell is wrong with this? // …

+ Read More