Wednesday 19 August 2015

Generic Best Practices in JAVA


1) Avoid using Raw types for new code. Always use Generics and write parametrized classes and method to get full benefit of compiler checking.

2) Prefer Collection classes over Array in your parametrized class because Generics and Arrays are completely different to each other, Array hold type information at runtime unlike Generics whose type information is erased by type-erasure during run time.

3) Use Bounded type parameter to increase flexibility of method arguments and API

4) Use @SuppressedWarning("unchecked") at as narrow scope as possible like instead of annotating a method, just annotate a line. Also document rational of why this cast is type-safe as code comments.


5) Convert your raw type classes into type-safe parametric class using Generics in Java as and when time allows, that will make code more robust.

Also you may like:

No comments:

Post a Comment

Featured post

How to convert Java object to JSON or JSON to java object in java

Download Gson jar from this link  Quick Reference toJson() – Convert Java object to JSON Gson gson = new Gson ( ) ; <Java cla...