Sunday, December 10, 2006

Writting Clear and Maintanable Java Code

This is my first technical java blog. Today I would like to share some ideas about how to write clear and maintainable code. As a Java developer we have to keep in mind some programming style considerations.General programming style considerations includes proper syntax, reusability of code, proper error-handling etc...

The syntax of a programming language tells you what code it is possible to write- what the machine will understand. Style tells you what you ought to write- what the humans reading the code will understand. Code written with a consistent, simple style will be secure, maintainable, robust and bug-free. We can make our application more strong by following some conventions. Here are summary of considerations, which I came across while going thru one of the chapters in Kathy Sierra’s book titled SCPD Java 2:

  • A class is supposed to represent a particular thing which has its own state and behavior, so while constructing class keep asking yourself, as you write each method, if that behavior might not be better suited for some other thing.
  • Keep variable scope as small as possible it means don’t use an instance variable when a local variable will work.
  • Consider overriding toString() to produce a useful description of the object. Use abstract classes when you need implementation functionality.
  • Use getters and setters that follow the Java Bean naming conventions.
  • Use Core APIs as it will lets you take advantage of a ton of expertise and testing, plus you are using code that hundreds of thousands of other Java developers are familiar with.
  • Avoid designing a class that has no methods, use proper design pattern, which is best suited to your application.
  • Use overloading rather than writing different logic and avoid long argument lists while encapsulating your class.
  • A good framework can sometimes help developers by avoiding you having to reinvent the wheel each time, but a bad framework is infinitely worse than no framework at all. Designing good frameworks is very, very hard. Consider this point carefully and draw your own conclusions.
  • Java is not C++. It's generally good practice not to check for error conditions all over the place unless you expect the condition to occur and plan to do something specific with that knowledge. Let the VM take care of array bounds and null pointer checking while you concentrate on your design.
  • Create and throw your own Exception when needed and for this keep in mind one thing that your exception should "Catch Low-Level Implementation Exceptions and Throw a Higher-Level Business Exception". Don’t return error codes. Use dialog boxes instead Excessive command-line messages.

No comments: