Blogs‎ > ‎

Useful tips and best practices


Useful tips and best practices

  • Implementing Comparable and understanding compareTo Implementing ComparableImplementing Comparable allows:Calling Collections.sort and Collections.binarySearch.Calling Arrays.sort and Arrays.binarySearch.Using objects as keys in a TreeMap.Using objects as elements in a TreeSet.Understanding compareToThe compareTo() method is the sole member of Comparable interface. It provides a means of fully ordering objects. For a concrete comparable implementation class to work well, the compareTo() implementation needs to satisfy the certain conditions.Anti Commutation :  x.compareTo(y) is the opposite sign of y.compareTo(x)Exception Symmetry : x.compareTo(y) throws exactly the same exceptions as y.compareTo(x)Transitivity :  if x.compareTo(y) > 0 and y.compareTo(z) > 0, then x.compareTo(z) > 0  (and same for less than)if x.compareTo ...
    Posted 17 Apr 2012, 00:06 by Sanjeev Kumar
  • Exception Handling Guidelines/Best Practices Let’s review some basic exception design guidelines, summarized from Object Design: Roles, Responsibilities, and Collaborations (Rebecca Wirfs-Brock and Alan McKean, Addison-Wesley, 2003).Don’t try to handle coding errors.Unless your software is required to take extraordinary measures in error scenarios, don’t spend a lot of time designing it to detect and recover from programming errors. In the case of an out-of-bounds array index, divide-by zero error, or any other programming error, the best strategy is to fail fast (and leave an audit trail of the problem that can be used to troubleshoot it).Avoid declaring lots of exception classes.Create a new exception class only when you expect some handling of the ...
    Posted 17 Apr 2012, 02:34 by Sanjeev Kumar
  • Creating Thread-Safe Singleton? A singleton class should be designed to ensures that there exists only one instance per application. Special care must be taken if your application is deployed on a clustered environment as in this case it is possible that multiple instance of your singleton class are available in your application.   Here are a few ways to create a thread safe singleton classes in your application. 1) Lazy loading Singleton instance - Using Synchronized method or blockpublic class SingletonClass{    private SingletonClass sc;    private SingletonClass(){}    public static SingletonClass getInstance(){        synchronized(SingletonClass.class) {              if (sc == null) {                  sc = new SingletonClass();              } else {                 return sc;              }        }    }}Issues- The use of synchronized keyword in a singleton class means that only one thread will be executing the synchronized block at ...
    Posted 16 Nov 2012, 10:45 by Sanjeev Kumar
  • Hot tips on using Eclipse effectively Following are some tips that shall help you in avoiding potential issues and for being a little more productive while working with eclipse. Avoid installation problems Never install a new version of Eclipse on top of an older version. Rename the old one first to move it out of the way, and let the new version be unpacked in a clean directory. Recovering your messed up workspace Corrupted workspace is a common occurrence and troublemaker for many developers. So If your Eclipse installation has startup errors or a corrupted configuration, it might be time to get a fresh start. Start Eclipse with the –clean option, and all cached framework and runtime data will be cleared out. This often helps fix ...
    Posted 30 Nov 2011, 01:41 by Sanjeev Kumar
  • Java 7 Updates It has been quite sometime that Java 7 got released with plenty of new features and enhancements that shall interest Java developer community. Following sections of this page cover some of these changes with examples. Strings in switch statementsIn the JDK 7 release, you can use a String object in the expression of a switch statement:public String getTypeOfDayWithSwitchStatement(String dayOfWeekArg) {     String typeOfDay;     switch (dayOfWeekArg) {         case "Monday":             typeOfDay = "Start of work week";             break;         case "Tuesday":         case "Wednesday":         case "Thursday":             typeOfDay = "Midweek";             break;         case "Friday":             typeOfDay = "End of work week";             break;         case "Saturday":         case "Sunday":             typeOfDay = "Weekend";             break;         default:             throw new IllegalArgumentException("Invalid day of the week: " + dayOfWeekArg);     }     return typeOfDay;}The diamond operator "<>"You can replace the type arguments required ...
    Posted 24 Nov 2011, 03:31 by Sanjeev Kumar
  • Use PMD - Programming Mistake Detector? About PMDHow do you ensure that your code follows standard programming principles? For most Java development projects going on these days the answer would be to use "PMD". It is aiming towards becoming a de-facto tool for analyzing the source code and is being used by more and more Java applications everyday. Note: There are a lot many tools that PMD competes with i.e Checkstyle, FindBugs, Hammurapi, Soot, Squale etc. However exploring capabilities of these tools(other than PMD) are out of scope of this article.PMD is a static rule set based Java source code analyzer that identifies potential problems in the code like:Possible bugs - empty try/catch/finally/switch statementsDead code - unused local ...
    Posted 19 Jan 2012, 09:00 by Sanjeev Kumar
  • Evolution of Java I thought it would be useful for architects, designers and developers to understand how Java has evolved since its inception so that they are aware of what all capabilities they have access to when working with a particular version of Java.  Besides, it is always good to have knowledge about evolution of the technologies that you are working with. 
    Posted 29 Nov 2011, 23:20 by Sanjeev Kumar
  • Choosing the right Collection Here is a quick guide for selecting the proper implementation of a Set, List, or Map in your application. The best general purpose or 'primary' implementations are likely ArrayList, LinkedHashMap, and LinkedHashSet. Their overall performance is better, and you should use them unless you need a special feature provided by another implementation. That special feature is usually ordering or sorting. Here, "ordering" refers to the order of items returned by an Iterator, and "sorting" refers to sorting items according to Comparable or Comparator.   Interface HasDuplicates? Implementations Historical Set no HashSet ... LinkedHashSet* ... TreeSet ... List yes ... ArrayList* ... LinkedList ... Vector, Stack Map no duplicate keys  HashMap ... LinkedHashMap* ... TreeMap Hashtable, Properties Principal features of non-primary implementations : HashMap has slightly better performance than LinkedHashMap ...
    Posted 4 Apr 2012, 11:01 by Sanjeev Kumar
  • Skip over certain classes when using Step Into(F5) in Eclipse’s debugger Whenever I use the Step Into feature (F5) in Eclipse’s debugger, I’m mainly interested in stepping through code in my own classes, not the ones from external libraries or even Java classes. For example, there’s almost no reason to ever want to step into Spring’s code or proxy classes (other than to learn more about them or maybe debug a potential bug in Spring). And normally I’m not interested in Java util classes (eg. ArrayList). This also goes for Hibernate, Apache Commons, Google and many other external libraries. Fortunately, Eclipse makes it easy to specify which classes to skip by allowing step filters. This makes it easier to focus on your own code and also ...
    Posted 11 Nov 2011, 05:59 by Sanjeev Kumar
  • Awesome place to access Java source code online I thought it would be useful to have quick access to entire java source code and for those open source projects that you don't have the source for while developing our java based applications. I came across this awesome link while searching for java source code online and now I visit it almost everyday. You can browse fully cross-references java source code from Maven repository just like you do in your IDE. I found it very useful and recommend it to every Java developer.http://www.mavenjava.com/NOTE: A JavaGyan reader "Kallol Das" pointed out that the link above seems to be dead from quite some time. www.kickjava.com is another alternative but that too has ...
    Posted 10 Nov 2012, 11:23 by Sanjeev Kumar
  • Using Eclipse Effectively To ensure that the code that you write is always clean and complaint to your project specific coding standards and guidelines, it is important that you configure your eclipse to effectively use its compiler settings, Formatter, CheckStyle and related built in features. Most developers wouldn't bother to do so but trust me that it is huge time saver in long run and shall always keep your code quality under check.Following spread sheet has the configuration that we use in our current projects. You can customize these settings according to your development standards and needs. Also ideally your Eclipse should be configured with your "code formatter" and "CheckStyle" XML configurations. To start with you can simply import these xmls ...
    Posted 11 Nov 2011, 06:00 by Sanjeev Kumar
  • Remote debugging on Jboss To debug your application on JBOSS server you would need to enable the debugging on your JBOSS application server. By default it is turned off. In order to set jboss app server to be running in debugging mode, you should uncomment following line in "jboss-5.1.0.GA/jboss/bin/run.conf"like this:# Sample JPDA settings for remote socket debuggingJAVA_OPTS=”$JAVA_OPTS -Xrunjdwp:transport=dt_socket,address=8787,serve Once done you can configure your eclipse remote application debugger on port 8787 and start debugging your application.Happy debugging !!
    Posted 11 Nov 2011, 06:01 by Sanjeev Kumar
  • Overloading can be tricky Extra care must be taken while writing Overloading methods. The compiler decides which version of an overloaded method will be called based on declared compile-time type, not run-time type. For the case in which overloaded methods have the same number of arguments, the rules regarding this decision can sometimes be a bit tricky.If there may be confusion, you may simplify the design:use different method names, and avoid overloading altogetherretain overloading, but ensure each method has a distinct number of argumentsIn addition, it is recommended that varargs not be used when a method is overloaded, since this makes it more difficult to determine which overload is being called.Reminder : Overloading requires methods with distinct signatures ...
    Posted 31 Dec 2010, 05:21 by Sanjeev Kumar
  • Crave for Immutable classes In the book "Effective Java", Joshua Bloch makes this compelling recommendation :"Classes should be immutable unless there's a very good reason to make them mutable....If a class cannot be made immutable, limit its mutability as much as possible."Immutable objects are objects whose data or properties cannot be changed after it is constructed. JDK has a number of immutable class like String and Integer. Immutable objects have big list of compelling positive qualities and they can greatly simplify your program. Immutable objects :are simple to construct, test, and useare automatically thread-safe and have no synchronization issuesdo not need a copy constructordo not need an implementation of cloneallow hashCode to use lazy initialization, and ...
    Posted 31 Dec 2010, 03:43 by Sanjeev Kumar
  • Quick tips to improve code quality in agile teams Here are a few quick pointers to improve code quality in agile teams and to deliver stories completely without leaving bugs behind.Improve how retrospectives are done so they can effectively detect and address these kinds of quality problems.If there are quality differences in the code written by different team members, have the better programmers find ways to raise the quality of code written by others.Focus on defect prevention, not just detection. Tools that can help are:code inspectionschecklistsUse pair-programming to improve knowledge sharing within the team. It seems expensive but mostly it is worth it.Begin regular use of static or dynamic code analysis tools.
    Posted 11 Nov 2011, 06:03 by Sanjeev Kumar
  • Package by feature, not layer The first question in building an application is "How do I divide it up into packages?". For typical business applications, there seems to be two ways of answering this question.Package by featurePackage by layerThe package-by-feature style seems to be the superior of the two (Read the full article on this topic) :Higher Modularity: As mentioned above, only package-by-feature has packages with high cohesion, high modularity, and low coupling between packages.Easier Code Navigation: Maintenance programmers need to do a lot less searching for items, since all items needed for a given task are usually in the same directory. Some tools that encourage package-by-layer use package naming conventions to ease the problem ...
    Posted 29 Nov 2011, 23:47 by Sanjeev Kumar
  • Beware of floating point numbers Outside of a scientific or engineering context, the use of float and double (and the corresponding wrapper classes Float and Double ) should likely be avoided. The fundamental problem is that rounding errors will always occur when using these data types - they are unavoidable.In a typical business application, using float and double to represent money values is dangerous, because of these rounding issues. Instead, BigDecimal should usually be used to represent money. It is also a common practice to have utility classes like "MonetaryAmount.java" that are wrappers over "BigDecimal" class of the JDK and that provides helper methods and functionality as needed by the business application.From an IBM article on this topic :"...binary floating-point arithmetic should not ...
    Posted 11 Nov 2011, 06:05 by Sanjeev Kumar
  • Use final liberally Use the final keyword liberally to communicate your intent. The final keyword has more than one meaning :a final class cannot be extendeda final method cannot be overriddenfinal fields, parameters, and local variables cannot change their value once setIn the last case, "value" for primitives is understood in the usual sense, while "value" for objects means the object's identity, not its state. Once the identity of a final object reference is set, it can still change its state, but not its identity. Declaring primitive fields as final automatically ensures thread-safety for that field.Some habitually declare parameters as final, since this almost always is the desired behaviour. Others find this verbose, and of little real ...
    Posted 18 Nov 2011, 09:57 by Sanjeev Kumar
  • Overridable methods need special care Allowing a method to be overridden should always be done intentionally, not by accident. Any method which is not private, static, or final can be overridden. Over-ridable methods, and any methods which call them, represent unusual places in your code, to which special attention must be paid. This is because sub-classing violates encapsulation, in the sense that it is possible for a subclass to break its superclass's contract. If you do not intend a method to be overridden, then you should declare it as private, static, or final.When you do override a method, you should use the @Override annotation. This allows the compiler to verify that the method is indeed a valid override of an existing ...
    Posted 11 Nov 2011, 06:08 by Sanjeev Kumar
  • Prefer composition over inheritance Trust me on this one, I have learnt it the hard way. To start with lets start with the understanding of the terms composition and inheritanceCompositionFunctionality of an object is made up of an aggregate of different classes.  In practice, this means holding a pointer to another class to which work is deferred.Collaboration is implemented simply by forwarding all calls to an object fieldit has no dependence on implementation details of the object fieldit is more flexible, since it is defined dynamically at run-time, not statically at compile-timeInheritanceFunctionality of an object is made up of it's own functionality plus functionality from its parent classes.Sub-classing or inheritance has the ...
    Posted 11 Nov 2011, 06:09 by Sanjeev Kumar
  • Converting Arrays to String Sometimes it may be required to display an array in string format. Expected result should be that all the elements of the Arrays gets printed out the way it is done for any collection. However the default toString() method is not very informative and does not include any array content. I have seen developers doing weird stuff to achieve this which includes writing helper methods and quite a few lines of code. However there are easier ways available with in Java API to achieve the same output. To provide more useful representations of arrays, various toString methods (and the deepToString method) were added to the Arrays class in JDK 1.5. Those methods can be used when available, as in ...
    Posted 11 Nov 2011, 06:10 by Sanjeev Kumar
  • Prefer switch over if-else In most cases switch will be lighter and performs faster than an if/else ladder. The compiler is able to optimize switch statements into a lookup table and perform compile-time checking for literals when dealing with enumerations, so I'd suggest that it's usually preferable to use switch over if/else if if you're dealing with numeric or enum types in Java. 
    Posted 11 Nov 2011, 06:11 by Sanjeev Kumar
  • Avoiding null pointer exceptions Null pointer exceptions(NPE) are the undoubtedly the most common and most annoying errors. In most cases I have observed that it could have been avoided by simply sticking to some best coding practices while writing code. Here is an example of a potential NPE.    // BAD CODE    private Boolean isExpired(final StatusEnum status) {        if (status.equals(StatusEnum.EXPIRED)) { // Potential null pointer if status is null.            return Boolean.TRUE;        } else {            return Boolean.FALSE;        }    }Here if the "status" that is passed to the method is null you will get a NPE at the first statement in the method. However if we write the code like as follows it can be avoided.    //GOOD CODE    private Boolean isExpired(final StatusEnum status) {        if (StatusEnum.EXPIRED ...
    Posted 17 Nov 2011, 09:10 by Sanjeev Kumar
  • Prefer using parameterized types over raw types When generics were introduced in JDK 1.5, raw types were retained only to maintain backwards compatibility with older versions of Java. Although using raw types is still possible, they should be avoided for following reasons :they usually require caststhey aren't type safe, and some important kinds of errors will only appear at runtimethey are less expressive, and don't self-document in the same way as parameterized typesUnless you are using a JDK version prior to 1.5 I don't see a reason why you should not use parameterized types in your code.Happy coding !!
    Posted 11 Nov 2011, 06:14 by Sanjeev Kumar
  • Eclipse Keyboard Shortcuts These keybindings are made by Carsten Ullrich (cullrich located-at activemath.org) and are released under the Creative Commons Attribution-ShareAlike 2.5 License (http://creativecommons.org/licenses/by-sa/2.5/).
    Posted 11 Nov 2011, 06:15 by Sanjeev Kumar
Showing posts 1 - 25 of 26. View more »

Comments