Category Archives: Best Practices

How to use decorator pattern, when the class to decorate is final

I have an inbuilt class in java – StringNow I have made 3 classes AddHashCode ToLowerCase AddLength I want to create a class, which has toString method overridden while selecting one or more of the above classes. For example:I want … Continue reading

Posted in Design Pattern | Leave a comment

Real time examples of Design patterns being used by Java

I am very keen to learn what all design patterns are being used by java code. So here I am going to list them one by one.. I’ll keep on updating this article as and when I learn more about … Continue reading

Posted in Best Practices, Design Pattern, Java | Tagged , | Leave a comment

Example of Decorator Pattern – LineNumberScanner

Create a LineNumberScanner like this public class LineNumberScanner implements Iterator{ Scanner sc; int i = 1; public LineNumberScanner(Scanner sc) { this.sc = sc; } public boolean hasNextLine() { return sc.hasNextLine(); } public String nextLine() { String nextLine = sc.nextLine(); if(nextLine==null) … Continue reading

Posted in Design Pattern | Leave a comment

Example of Decorator Pattern – LineNumberReader

Create a LineNumberReader like this public class LineNumberReader extends BufferedReader { int lineNo = 1; public LineNumberReader(Reader in) { super((BufferedReader)in); } public void close() throws IOException { in.close(); } /* * Add more responsibility of adding a line Number in … Continue reading

Posted in Design Pattern | Leave a comment

Example of Decorator Pattern – LowerCaseInputStream

Create a LowerCaseInputStream class as follows public class LowerCaseInputStream extends FilterInputStream { public LowerCaseInputStream(InputStream in) { super(in); } @Override public int read() throws IOException { int c = super.read(); if(c==-1) return c; else return Character.toLowerCase(c); } @Override public int read(byte … Continue reading

Posted in Design Pattern | 2 Comments

Best Practices while writing Java code

Usually many of us write the java code in a try-catch block as follows try{ // some code here}catch(Exception e){ // log exception here} Better way to do it is try{ // some code here}catch(Exception e){ // log exception here}catch(Throwable … Continue reading

Posted in Best Practices, Design Pattern, Java, Server Side Programming | Tagged , , | Leave a comment

Best practices in Collections

If you do need a synchronized map, you can use the static method synchronizedMap(…) in class Collections to add synchronization to a regular map. Don’t use the legacy collection classes, such as Hashtable. Example: // A regular, unsynchronized map Map … Continue reading

Posted in Best Practices | Leave a comment