Why should you use Unchecked exceptions over Checked exceptions in Java



The debate over checked vs. unchecked exceptions goes way, way back. Some say it’s one of the best features Java included. Others say it was one of their biggest mistakes[1].

It looks like the debate is over. In this post I will try to include the links to articles and books which speaks about this topic. I am not an expert voice in this, but I will try to explain you why did I reach the this conclusion.

So, we are talking about,

Unchecked exceptions :
  • represent defects in the program (bugs) - often invalid arguments passed to a non-private method. To quote from The Java Programming Language, by Gosling, Arnold, and Holmes : "Unchecked runtime exceptions represent conditions that, generally speaking, reflect errors in your program's logic and cannot be reasonably recovered from at run time."
  • are subclasses of RuntimeException, and are usually implemented using IllegalArgumentException, NullPointerException, orIllegalStateException
  • a method is not obliged to establish a policy for the unchecked exceptions thrown by its implementation (and they almost always do not do so)
Checked exceptions :
  • represent invalid conditions in areas outside the immediate control of the program (invalid user input, database problems, network outages, absent files)
  • are subclasses of Exception
  • a method is obliged to establish a policy for all checked exceptions thrown by its implementation (either pass the checked exception further up the stack, or handle it somehow)
The above are as told in Java Practices Page[2].


In many of the projects I have worked on, I have seen different ways of coding and various different strategies, code formatting, class naming styles, databases and technologies. The one thing that remained same was, Exceptions. All the projects had custom exceptions, created by extending Exception class!

I am sure that most us of know the difference between checked and unchecked exceptions, but very few thinks carefully before using them. I wanted all the details to be listed in single page so that I could convince my team to switch to Unchecked  exceptions.

In his famous book, Clean code: a handbook of agile software craftsmanship[3], Robert C. Martin writes the below lines supporting Unchecked Exceptions.

The debate is over. For years Java programmers have debated over the benefits and liabilities of checked exceptions. When checked exceptions were introduced in the first version of Java, they seemed like a great idea. The signature of every method would list all of the exceptions that it could pass to its caller. Moreover, these exceptions were part of the type
of the method. Your code literally wouldn’t compile if the signature didn’t match what your code could do.

At the time, we thought that checked exceptions were a great idea; and yes, they can yield some benefit. However, it is clear now that they aren’t necessary for the production of robust software. C# doesn’t have checked exceptions, and despite valiant attempts, C++ doesn’t either. Neither do Python or Ruby. Yet it is possible to write robust software in all of these languages. Because that is the case, we have to decide—really—whether checked exceptions are worth their price.

Checked exceptions can sometimes be useful if you are writing a critical library: You must catch them. But in general application development the dependency costs outweigh the benefits

The last line is most significant, where he speaks about the general application  development, Lets take an example,


If you have to read an XML file using a DOM Parser, we need to deal with some checked exceptions[5] like ParserConfigurationException, SAXException and IOException . The API developer thought that if the XML was invalid, they should notify so that the consumer of the API(ie, the application developer) can decide how to handle the situations.

Now, If You have some alternatives to proceed with the normal logic, you could do that, other wise you should catch these checked exceptions and throw and Unchecked exception. This way the method signatures will be clean also, we are stating that if the XML is invalid we are can not do much, and we are stopping the processing. Let the error handler written at the top layer take the appropriate decision on what to do.

So, all we need to do is to create out custom exception class by extending RuntimeException.

In the Java Tutorial hosted by Oracle, there is an interesting page about this debate[4], the page ends with the line, If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception.

I have also found few article supporting this,


The Tragedy Of Checked Exceptions by Howard Lewis Ship
Exceptions are Bad  by  Jed Wesley-Smith


Also, few articles on general exceptional best practices,


Guidelines Exception Handling By Vineet Reynolds
Exceptional practices  By Brian Goetz

Useful Eclipse Plugins that didn't make it to the Top 10 list



Eclipse IDE project is started aiming to provide a universal tool set for development. Open Source IDE, mostly provided in Java, but the development language is independent. Eclipse market place hosts the list of plugins for the worlds most popular IDE. You can see the Top MPC Downloads and Top Favorites plugins are highlighted in the site. In this post I will introduce you some of the coolest eclipse plugins that I have used but were not part of the Top 10 list shown in the marketplace.

Below are my favorite plugins which are already listed in the top 10 list.

1. Spring Tool Suite
2. Maven Integration for Eclipse
3. Subclipse
4. UMLet
5. FindBugs
6. CheckStyle
7. AnyEdit

Givern below the ones that don't made it to the top 10 list but can make it one day!

General Purpose Tools

1. Rabbit

Rabbit is a time tracking plug-in for Eclipse. It runs silently in the background to record how you spend your time within Eclipse and reports the data back to you whenever you want it to - in a useful way.

2. InstaSearch

InstaSearch is an Eclipse plug-in for doing fast text search in the workspace. The search is performed instantly as-you-type and resulting files are displayed in an Eclipse view. It is a lightweight plug-in based on Apache Lucene search engine. Each file then can be previewed using few most matching and relevant lines. A double-click on the match leads to the matching line in the file.

3. EasyShell

This plugin allows to open a shell window or file manager from the popup menu in the navigation tree or editor view. The current directory of the opened shell is the directory which was selected with the popup menu. Additionally it is possible to run selected file in the shell and copy file or directory path. Multiple selections are also supported.

4. Eclipse Todo Editor

Manage your todos in an easy to use text editor with syntax highlighting and code completion. Effectively structure and query your todo lists using projects and custom tags. 

5. MailSnag

With MailSnag, you can debug application generated emails within Eclipse. MailSnag creates a simple SMTP server to capture and inspect emails sent out by an application during development. You can view the email rendered as HTML, text or both. You can also view the raw data, embedded content and attachments.

6. More Clipboard

More Clipboard keeps track of the latest entries copied/cut into clipboard buffer and allows quick pasting from the popup list by pressing a hotkey. Inspired by Multi Clipboard plugin for Eclipse and Visual Assist for MS VS.

7. ObjectAid UML Explorer 

The ObjectAid UML Explorer is optimized for the quick and easy creation of UML class and sequence diagrams from existing Java source code and libraries. It uses the UML notation to show a graphical representation of existing code that is as accurate and up-to-date as your text editor.

8. AgileReview

AgileReview provides you with an easy possibility to do code reviews in your favorite IDE. Code reviews are a powerful meaning for quality assurance, but switching between spreadsheets and code is very time consuming. With AgileReview you can comment and discuss code without leaving the IDE and more important: without leaving the code.


Tools for Java Developers

9. JAutodoc

JAutodoc is an Eclipse Plugin for automatically adding Javadoc and file headers to your source code. It optionally generates initial comments from element name by using Velocity templates for Javadoc and file headers.

10. JadClipse

 If you use JadClipse the Class File Viewer will be replaced with the JadClipse Class File Viewer that shows the decompiled source of the class. This task is accomplished by decompiling the corresponding class file in the background using Jad. Normal Java syntax highlighting as well as the Outline View are supported.

Unit Testing

11. JUnit Helper

"JUnit Helper" helps JUnit users to cover all tests for public, protected and package local methods by saving much labor to start writing new test cases. Eclipse plugin also has an advantage of making it easier to go back and forth between developing class and test class by "Alt + 8" (test->dev) and "Alt +9"(dev->test).

12. MoreUnit

MoreUnit is an eclipse plugin that should assist you writing more unit test. The following features are implemented: - Decorate classes which have a testcase. - Mark methods in the editor which are under test. - Jump to a testcase in the editor via the menu or a shortcut (and back) - Generate a testmethod stub for the method under cursor-position in the editor via the menu or a shortcut. - Rename/move of classes / methods with corresponding testcases automatically starts refactoring for tests as well.

Looging Helpers

13. Logging code Cleanup for Eclipse

Logging code Cleanup plugin for Eclipse is an extension of the Eclipse Cleaun Ups which detects invocations of logging methods with compound arguments (requiring computation before method call) and prefixes them with corresponding if statements.

14. Log4E

Log4E is an Eclipse Plugin which helps you to set up your logger easily in Java Projects. It assists you in several tasks: logger declaration, logger Insertions at certain method entries, substitution of System out's, modification of already existing logger statements. Log4E has active support for Log4j, Commons Logging and JDK 1.4 Logging. By defining your own templates you might be able to adapt your own logger to the Plugin. 

UML and Code Analysis Tools

15. ModelGoon UML4Java

ModelGoon brings new points of view of a Java project. Thanks to its tight connection and interaction with the Eclipse Java Development Tools JDT. ModelGoon provides also round-trip features on Class Diagrams actually as beta.

16. CodePro AnalytiX

CodePro AnalytiX is the premier Java software testing tool for Eclipse developers who want to be active participants in improving the quality and security of the code they produce. CodePro AnalytiX seamlessly integrates into the Eclipse environment, using automated source code analysis to pinpoint quality issues and security vulnerabilities before code reaches QA, or worse, production!

17. Sonar

Sonar for Eclipse provides comprehensive integration of Sonar into Eclipse. It shows quality issues while browsing the source code. Developers are made aware of quality issues compared to corporate standards without leaving their favorite IDE and thus enabling for continuous improvement with no effort. No propagation of standards changes is required anymore as definition is centralized.

18. MaintainJ

MaintainJ generates the runtime sequence diagrams for a use case. MaintainJ generated diagrams are dynamic, easy to explore and help Java developers to understand, debug and document Java applications.

19. EclEmma Java Code Coverage

EclEmma is a free Java code coverage tool for Eclipse, available under the Eclipse Public License. It brings code coverage analysis directly into the Eclipse workbench

20. eCobertura

eCobertura enables you to launch your applications or tests in Cobertura-covered mode directly from within Eclipse. View your source files colored according to the coverage results. Browse through the detailed coverage results in a tree view.

Note:- The numbering is arbitrary and does not imply the importance. The description about each plugins is copied from the Eclipse Market Place.

Upgrading Tapestry version from 5.0.18 to 5.2.5: Issues and Resolutions



In this post I am going to write about the issues that we have faced during the up-gradation of the tapestry version from 5.0.18 to 5.2.5 in one our projects. Below are some of them. Hope this collection will help someone!


1. Changes in the RequestPathOptimizer file inside tapestry.


Issue Logs:-


Caused by: java.lang.ClassNotFoundException: org.apache.tapestry5.internal.services.RequestPathOptimizer from BaseClassLoader@41c491{VFSClassLoaderPolicy@1d02b85{name=vfsfile:/D:/SVN/trunk/export/tools/jboss-5.0.1.GA/server/default/deploy/ROOT.war/ .......
at org.jboss.classloader.spi.base.BaseClassLoader.loadClass(BaseClassLoader.java:422)


Solution:-


Remove all the tapestry-spring dependancies to resolve this issue.


Reference:-


Tapestry JIRA 
Mailing list URL 




2.Including the tapestry bean validator jar.


Logs:-


Caused by: java.lang.ClassNotFoundException: javax.validation.ValidatorFactory from ......
..............
real=file:/D:/SVN/trunk/export/tools/jboss-5.0.1.GA/server/default/deploy/ROOT.war/WEB-INF/lib/XmlSchema-1.4.2.jar]] delegates=null exported=[]}} at org.jboss.classloader.spi.base.BaseClassLoader.loadClass(BaseClassLoader.java:422)


Solution:-


There is new feature in Tapestry called bean validator that needs the validation api and implementation jars to be added it can be downloaded from the project homepage here.


3.Changes in the tapestry spring integration.


Logs:-


Caused by: java.lang.IllegalStateException: Cannot initialize context because there is already a root application context present - check whether you have multiple ContextLoader* definitions in your web.xml!
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:179)
at org.apache.tapestry5.internal.spring.SpringModuleDef$3$1.invoke(SpringModuleDef.java:194)
at org.apache.tapestry5.ioc.internal.OperationTrackerImpl.invoke(OperationTrackerImpl.java:65)
... 91 more
java.lang.RuntimeException: Exception constructing service 'ApplicationContext': Cannot initialize context because there is already a root application context present - check whether you have multiple ContextLoader* definitions in your web.xml!


Solution:-


From Tapestry 5.2.x it will load the spring context automatically and hence we need to remove the below from web.xml. This will help in live class loading of service class. Also the spring beans should be wired and not to be injected as services.As per this there will be changes in All the Page classes and web.xml


Reference:-


Mailing list URL
Tapestry Wiki-1 
Tapestry Wiki-2


As per the article "The changes below represent an unfortunate backwards compatibility issue. If necessary, you can still use tapestry-spring version 5.0.18 with the rest of Tapestry."


If we want to continue using spring-tapestry 5.2.5 jar we have to make changes in each and every Page file where spring services are injected. Also the spring beans should be wired and not to be injected as services.




4. Using Tapestry 5.2.5 inside the JBoss Application server.


Logs:-


Caused by: java.io.IOException
at org.jboss.virtual.plugins.registry.DefaultVFSRegistry.getFile(DefaultVFSRegistry.java:125)
at org.jboss.virtual.protocol.AbstractVFSHandler.openConnection(AbstractVFSHandler.java:71)
at java.net.URL.openConnection(Unknown Source)
at java.net.URL.openStream(Unknown Source)
at org.apache.tapestry5.ioc.internal.services.ClassNameLocatorImpl.scanDirStream(ClassNameLocatorImpl.java:182)
at org.apache.tapestry5.ioc.internal.services.ClassNameLocatorImpl.scanURL(ClassNameLocatorImpl.java:131)
at org.apache.tapestry5.ioc.internal.services.ClassNameLocatorImpl.findClassesWithinPath(ClassNameLocatorImpl.java:96)
at org.apache.tapestry5.ioc.internal.services.ClassNameLocatorImpl.locateClassNames(ClassNameLocatorImpl.java:75)
... 85 more
Caused by: java.net.URISyntaxException: Illegal character in path at index 159: vfszip:/D:/SVN/trunk/export/tools/jboss-5.0.1.GA/server/default/deploy/ROOT.war/WEB-INF/lib/tapestry-upload-5.2.5.jar/org/apache/tapestry5/upload/components/PK/
at java.net.URI$Parser.fail(Unknown Source)


Solution:-


As per the below links we need to use a patch to fix it.


Mailing list URL-1
Mailing list URL-2 
Tapestry JIRA
Tapestry Wiki



5. Changes in the Locale implementation


If you use the url to load pages and your application supports the multiple languages then you need to append the locale code infront of the url.


For example:
Current url: "http://localhost/superpopup" should be changed to "http://localhost/${localeInd}/superpopup" 


Mailing List URL  


6. Tapestry handling of transients instances ValueEncoder


Mailing List URL


7. Change in the way @Secure is handled in the page classes.


Most of the applications we will have the Index page tagged with the @Secure annotation to force the usage of https protocol. Some how I could not get this done with the existing settings. To have this you need to add the below lines.


configuration.add(SymbolConstants.SECURE_ENABLED, "true");


Mailing List URL


When to replace Unit Tests with Integration Test


Its been a while I was thinking about integration vs unit testing. Lots of googling, questions in stack overflow and looking in many books. In this post I would like share with you the information I have found and what decision I arrive at this.


I think if you put this question to any Java developer, you will get an anwser supporting the unit test instantaneously. They will tell you that if you can not do unit testing, the unit of code you hava written is large and you have to bring it down to multiple testable unit. I have found these questions in Stack Overflow 1, 2, 3 and 4 useful in getting a good understanding of both terminologies.

Unit testing is widly followed in Java domain with most of the projects now also enforcing the code coverage and unit testing. Integration testing is relativly new and misunderstood concept. Even through it is practiced much less than, unit testing there can be varios uses of it. Lets take a simple user story and revisit both.

Lets consider it with a user story

User will give an INPUT in a UI form and when the submit button is clicked, the PROCESSED output should be shown in the next page. Since the results should be editable, both INPUT and OUTPUT should be saved in the database.

Technical Design

Lets assume that our application will grow rapidly in the future and we will design it now keeping that in mind. 


As shown in the above image it is a standard 4-tier design with view, service, dao. It has a application layer which contains the logic of how to convert the input into output. To implement the story we wrote 5 methods(1 in service, 2 dao to save input and output, 1 contains the business and 1 method in view layer to prepare the input.)

Writing some Unit test cases

If we were to unit test the story, we need to write 5 tests. As the different layers are dependent, we might need to use mock objects for testing. But apart from one method in application layer that does the original process, is there any need to unit test the other part? For example the method,

 public void saveInput(Input input){  
           Session session = sessionFactory.getCurrentSession();  
           session.save(input);  
 }  


When you unit test this, you will typically use a mock object of sessionFactory and the code willl always work. Hence I don't see much point in wiring a unit test here. If you observe carefully, apart from the application layer, all the other methods will be similar to what we have discussed.


What can we acheive with integration test?


Read here as a heads up for the integration test. As we have seen most of the unit tests for this story were not effective. But we can't skip testing as we want to find out the code coverage and make our code self testing. According to Martin flower in his article about Continuous Integration you should write the code that can test the other code. I fell the good integration tests can do this for you.


Lets write a simple itegration test for this situation,

 @Configurable(autowire = Autowire.BY_NAME)   
 @RunWith(SpringJUnit4ClassRunner.class)   
 @ContextConfiguration(locations = {"classpath:applicationContext.xml"})  
 public class SampleIntTest {  
      @Autowired  
      private SamService samService;  
      @Test  
      public void testAppProcessing(){  
      Input input = new Input();  
      //prepare input for the testing.  
      Output output = samService.processInputs(input);  
      //validate outpt gainst the given input.  
      if(!isValidate(input,output)){  
           Assert.fail("Validation failed!");  
      }  
 }  



I have skipped the view layer here as it not so relevent. We are expecting the INPUT from the UI in a bean Input and thats that we willl have in the service layer. Here, With this few line of coding, you can acheive the full functionality of the application from the service layer.


It is prefered to use a in-memory database like H2 for integration tests. If the table structure is complicated it may not be possible in that case,you can use a test instance of DB and prepare a script to delete all the data and run it as part of the test so that the DB state is restored back. This is important because in the next run the same data will be saved again.


Another advantage of integration tets is that if you are changing the implementation the test need not be changed because it ic concerned with the input and output.This is useful in refactoring the code without change in the test code. Also, you can schedule these tets to measure the stability of the appication and any regression issues can be caught early.


As we have seen, integration test are easy to write and are useful, but we need to make sure it does not replace the unit testing completely. When ever there is a rule base system(like the LogicalProcesser in our case) it should be mandatory because you can't cover all the scenarios with the integration test.


So as always JEE is about making choice asnd sticking to it. For the last few months we were practicing it in our teams and it is really going well. Currently we made integration test mandatory and unit tests and optional. Always review the code coverage and make sure you get good coverage in the core of the system(the LogicalProcesser in our case).

Developing Java Web Applications with Tapestry 5



In this post I would like to share my experience with  developing Java Web Applications with Tapestry 5.

Tapestry is a component oriented framework for creating dynamic, robust, highly scalable web applications in Java. Tapestry is been is here for a while now, not really taken off as a web framework for Java. In the past, it is been critisized for non compatability of its versions. After the release of version 5 in 2008 it has been more consistant and popular with developers.

I have been using Tapestry for the last 15 months and used both version 5.0.18 and 5.2.6. One of the main issues with tapestry was the learning curve and that is been some what improved now, with the exelent documentation available at the project home page here. You don't see  a lot of tapestry resources online. If you search for the tapestry resources in internet you might end up getting t3 or t4 versions which will not be usefull with the new t5 version.

Having worked in tapestry for more than one year, I must say that I have mixed opinion about tapestry. Its POJO based approach is really nice and it also scores as a component based framework. The components are easily plug-gable in all the pages. There has been a lot of improvements in the ability of unit testing the pages. Even if you don't want to depend on tapestry's test classes you can create your own integration test cases as the pages are simple java classes. It has really good integration with spring that opens your window to all other frameworks and technologies.

The biggest pain is been when you are stuck with problems, the alternatives were really difficult. For example there is a grid component in tapestry which by default provides sorting for all the columns in the grid. If you need to disable sorting, there should be hell lot of things you have to do as told here. In another example, you might need to have 3 classes construct a simple drop down in tapestry as told here. In today world of IDE tapestry don't have much of IDE support and that can be a pain while you develop a page in tapestry.

Its been really difficult to find good resouces about tapestry and I thought of sharing some links that I found useful during my learning of tapestry. As I told already the getting started page is reaaly improved and now you can really get started with tapestry in that page. The wiki page contains lots of tips and tricks on how to use tapestry features.

The Tapestry Jump Start page is great place with lots of examples that will help you get into tapestry. Howard M. Lewis Ship the creator of Tapestry writes about tapestry in his personal blog is also a good read.  Recently I have found another site with lots of exapmle in tapestry.  Even the Tapestry360 is a fresh and new concept.I  really liked Mark Shead blog post is a good collection of usefull references about tapestry5.

When you are thinking about java web framework I think tapestry should be one of the choices. If You compare tapestry with other web framework there will be lots of diffidence have a look at Matt Raible presentation about comparing jvm web frameworks also the matrix comparing the web frameworks in Java. Also there is a post from Joshua about why you should consider tapestry5.

Top 10 Java Books you don't want to miss.




We learn by reading books and experimenting on it.  So, it is imperative that you choose the best available options. In this post I would like to share my experience with some of the books and how they can help you evolve as a Java Developer.

Lets start from the floor, the first 3 books are a good starting point for any Java student. Java Programming Language helps you to get yourself familiar with Java, where Head First will help you stick the Java concepts into your brain, so that you will never forget them. I have chosen Thinking In Java 3rd book in this category but Java the Complete Reference By Herbert Schildt and Java in a nutshell  By David Flanagan are good substitutes. These books are more of a reference than a must read.


1. Java Programming Language By Ken Arnold, James Gosling, David Holmes
               
                Direct from the creators of the Java, The Java Programming Language is an indispensible resource for novice and advanced programmers alike. Developers around the world have used previous editions to quickly gain deep understanding of the Java programming language, its design goals, and how to use it most effectively in real-world development. The authors systematically conver most classes in Java's main packages, java.lang.*, java.util, and java.io, presenting in-depth explanations of why these classes work as they do, with informative examples. Several new chapters and major sections have been added, and every chapter has been updated to reflect today's best practices for building robust, efficient, and maintainable Java software.

Above are extracts from the book index page.

2. Head First Java By Kathy Sierra, Bert Bates
               
                Its unique approach not only shows you what you need to know about Java syntax, it enables and encourages you to think like a Java programmer. Mastering object oriented programming requires a certain way of thinking, not just a certain way of writing code. The latest research in cognitive science, neurobiology, and educational psychology shows that learning at the deeper levels takes a lot more than text on a page. Actively combining words and pictures not only helps in understanding the subject, but in remembering it. According to some studies, an engaging, entertaining, image-rich, conversational approach actually teaches the subject better. Head First Java puts these theories into practice with a vengeance.

Above lines are copied from Google books read more here.
               
3. Thinking In Java By Bruce Eckel
               
                Eckel introduces all the basics of objects as Java uses them, then walks carefully through the fundamental concepts underlying all Java programming -- including program flow, initialization and cleanup, implementation hiding, reusing classes, and polymorphism. Using extensive, to-the-point examples, he introduces exception handling, Java I/O, run-time type identification, and passing and returning objects. Eckel also provides an overview of the Key Technology of the Java2 Enterprise Edition platform (J2EE).

Above lines are copied from Google books read more here.               


I am not a big fan of SCJP Exam, but A Programmer's Guide to Java SCJP Certification is much more than a certification guide. It gives you an insight in to Java, the tips and tricks. SCJP Sun Certified Programmer for Java 5 Study Guide  By Kathy Sierra, Bert Bates is a go to book if you are mad about SCJP. Better to read these books than spending time in reading question dumps, these books will help you much more than clearing the exam in your career.
               
4. A Programmer's Guide to Java SCJP Certification: A Comprehensive Primer By Khalid Azim Mughal, Rolf Rasmussen
               
                 This book will help you prepare for and pass the Sun Certified Programmer for the Java Platform SE 6 (CX-310-065) Exam. It is written for any experienced programmer (with or without previous knowledge of Java) interested in mastering the Java programming language. It contains in-depth explanations of the language features. Their usage is illustrated by way of code scenarios, as required by the exam. Numerous exam-relevant review questions to test your understanding of each major topic, with annotated answers Programming exercises and solutions at the end of each chapter Copious code examples illustrating concepts, where the code has been compiled and thoroughly tested on multiple platforms Program output demonstrating expected results from running the examples Extensive use of UML (Unified Modelling Language) for illustration purposes

Above lines are copied from Google books read more here.               

               
OK, so you got to know Java and been working in it for couple of years its time to take the next step. Everything in this world has good and bad. Java language if not used the way is supposed to be, can make your life miserable. When you write code, its written for future. Writing good Java code is an art that needs lot more skill than knowledge of basic Java. Here I would like to introduce the next set of 4 books that can make you a master in the trade.
                
The Pragmatic Programmer is not really a Java book but is a self help book for any programmer. It is a great book covering various aspects of software development and is capable in transforming you to a Pragmatic Programmer.
               
5. The Pragmatic Programmer, From Journeyman To Master By Andrew Hunt, David Thomas

                Written as a series of self-contained sections and filled with entertaining anecdotes, thoughtful examples, and interesting analogies, The Pragmatic Programmer illustrates the best practices and major pitfalls of many different aspects of software development. Whether you're a new coder, an experienced programmer, or a manager responsible for software projects, use these lessons daily, and you'll quickly see improvements in personal productivity, accuracy, and job satisfaction. You'll learn skills and develop habits and attitudes that form the foundation for long-term success in your career. You'll become a Pragmatic Programmer.
               
Above lines are copied from Google books read more here.               


So, we wrote code. It is time to add some style. The elements of Java style is one of the earliest documentation on the style part of Java including its various aspects.
               
6. The elements of Java style By Scott Ambler, Alan Vermeulen

                 Many books explain the syntax and basic use of Java; however, this essential guide explains not only what you can do with the syntax, but what you ought to do. While illustrating these rules with parallel examples of correct and incorrect usage, the authors offer a collection of standards, conventions, and guidelines for writing solid Java code that will be easy to understand, maintain, and enhance. Java developers and programmers who read this book will write better Java code, and become more productive as well.

Above lines are copied from Google books read more here.
              

Now, we know how to write code in style. But is it best is class? Does it uses the best practices? Effective Java is one of the best book on best practices is a favourite book for many Java developers.
               
7. Effective Java By Joshua Bloch

                Joshua  brings together seventy-eight indispensable programmer's rules of thumb: working, best-practice solutions for the programming challenges you encounter every day. Bloch explores new design patterns and language idioms, showing you how to make the most of features ranging from generics to enums,  annotations to autoboxing. Each chapter in the book consists of several “items” presented in the form of a short, standalone essay that provides specific advice, insight into Java platform subtleties, and outstanding code examples. The comprehensive descriptions and explanations for each item illuminate what to do, what not to do, and why.

Above lines are copied from Google books read more here

Then, you know the good, it is time for the bad stuff. Bitter Java is one of the first book to bring up the Anti-patters in Java. There are various articles and books on Anti-patterns and code smells and is an area where there is lots of space to learn. There are many other books on this topic I am adding this book as a starting point.
               
8. Bitter Java By Bruce Tate

                Intended for intermediate Java programmers, analysts, and architects, this guide is a comprehensive analysis of common server-side Java programming traps (called anti-patterns) and their causes and resolutions. Based on a highly successful software conference presentation, this book is grounded on the premise that software programmers enjoy learning not from successful techniques and design patterns, but from bad programs, designs, and war stories -- bitter examples. These educational techniques of graphically illustrating good programming practices through negative designs and anti-patterns also have one added benefit: they are fun.
               
Above lines are copied from Google books read more here

Many say you need to know Design Patterns, if you want grow as a developer. So I thought of mentioning the best Design pattern book that I have read. It is not a reference book nor it contains the patters catalogue but the book explains the Object Oriented Design Principles that are as important as the patters. Use the book Design patterns: elements of reusableobject-oriented software if you are looking for a reference book.
               
9. Head First design patterns By Eric Freeman, Elisabeth Freeman, Kathy Sierra, Bert Bates

                You know you don't want to reinvent the wheel (or worse, a flat tire), so you look to Design Patterns--the lessons learned by those who've faced the same problems. With Design Patterns, you get to take advantage of the best practices and experience of others. Using the latest research in neurobiology, cognitive science, and learning theory, Head First Design Patterns will load patterns into your brain in a way that sticks. In a way that lets you put them to work immediately. In a way that makes you better at solving software design problems, and better at speaking the language of patterns with others on your team.
               
Above lines are copied from Google books read more here

If your are a master at coding and designing application using Java its time to crack the JVM. I have read that 'The Java language specification' is the best book to do that. I have not got the patience or skill to read the book but is an interesting pick if you want to cross the line.
               
10. The Java language specification

                The book provides complete, accurate, and detailed coverage of the Java programming language. It provides full coverage of all new features added in since the previous edition including generics, annotations, asserts, autoboxing, enums, for each loops, variables,  methods and static import clauses.

Above are extracts from the book index page.

In these web-years online resources may be more reachable than books, but I fell these books will help in tuning you to a better Java programmer.

Hibernate Data Fetching Options




In this post I will try to point out various ways you can fetch data in hibernate and in what scenarios each of then are is useful.


HQL in hibernate
It is the most preferred way to use that combines you the ease of SQL and flexibility of Hibernate. I don't want to add anything more but will direct you to an excellent article on HQL.


Criteria Queries
Criteria queries are less verbose and preferred by people who don't have much exposure to SQL. It is less performative compared to HQL. Read more about Criteria here.


Native SQL and Stored Procedures.
This should considered as a last option as you will loose the features of hibernate if you start using Native SQL.Also you should take care the responsibility of transforming the result set to object by yourself.
But there are situations you want to go with this approach. Read more about them here.

These typical ways can be tweaked in various ways to customize them to your requirement. Let me discus few of them that you may not find very often documented.

I have used the classes from examples from my previous post for simplicity.Read it here in case you need any explanation on the examples.

1. Partial Initialization of a bean.

Suppose you have a bean AMain, as in my previous post.

 public class AMain {  
    Integer aId;  
    String name;  
    ASub1 one2oneSubA1;  
    List<ASub3> subList;  
      //More code below...  
 }  

If you write an HQL to fetch this bean as 


 List<AMain> beanList2 = session.createQuery("from AMain am ").list();  


it will fire the below queries.


Hibernate: select amain0_.a_id as a1_1_, amain0_.name as name1_, amain0_.prop1 as prop3_1_, amain0_.prop2 as prop4_1_, 'A' as formula0_, amain0_.a_id as formula1_ from A_Main amain0_
Hibernate: select asub1x0_.as1_id as as1_2_0_, asub1x0_.sub_name as sub2_2_0_, asub1x0_.a_id as a3_2_0_ from A_Sub1 asub1x0_ where asub1x0_.a_id=?
Hibernate: select sublist0_.a_id as a3_1_, sublist0_.as3_id as as1_1_, sublist0_.as3_id as as1_4_0_, sublist0_.sub_name as sub2_4_0_, sublist0_.a_id as a3_4_0_ from A_Sub3 sublist0_ where sublist0_.a_id=?

 Also the last query can repeat number of times if the lazy loading in enabled.

Now If I have a requirement to get the partially initialized AMain bean, I mean with only the properties aId and name initialized that definitely should not take mare than 1 query as all the information is available on the AMain table. Most of the people will tend to go to Native SQL at this point.But you can achieve this using HQL.


write the HQL as   

 List<AMain> beanList2 = session.createQuery("select new AMain (aId,name) from AMain am ").list();  


Also add the corresponding constructor in class AMain as

 public AMain(Integer aId,String name) {  
           this.aId = aId;  
           this.name = name;  
      }  




Now verify the SQL output


Hibernate: select amain0_.a_id as col_0_0_, amain0_.name as col_1_0_ from A_Main amain0_


Yes..only 1 query is fired.This is very useful in when we have to fetch a snapshot of a Large object in a performative way.




2. HQL Joins on multiple columns.


If there are two related table and we have mapped them in the hbm files then the below hql is possible.


"from AMain a left outer join a.refMain ref...more joins here"


It will do a left outer join on the tables RefMain and AMain provided you have a corresponding mapping. Now if you need to add another condition in the join(to satisfy the join but which we could not add as a relationship). It can be achieved using a 'with' operator.


so, the new HQL is,


"from AMain a left outer join a.refMain ref with ref.aOrbId = 'a'...more joins here"


This way the query results can be achieved with out disturbing the original mapping.


3. Using a DTO instead on a Domain Object.

Meany times we might need a set of data that might be needed which is spread across multiple tables. Which means I don not have a Domain Object to hold the data. Using hibernate we can populate a DTO object from any SQL of HQL query using Transformers. The Transformers can convert the List of Object arrays to List of DTO that will improve the readability and are much easier to use with.

 public class AFamilyDTO {  
      Integer aId;  
      String name;  
      Integer as1Id;  
      String aSub1Name;  
      /* getter/ setters here..*/   
 }  


As you can see the bean represent a snapshot of AMain and ASub1 beans Or it can be any DTO which we have created for the easy representation of the data model. Now Lets see how we can use Transformers to populate this bean.

 SQLQuery query = session.createSQLQuery("select amain.a_id as aId , amain.name as name, " +  
               "sub1.as1_id as as1Id, sub1.sub_name as as1Name " +  
               " from A_Main amain join A_Sub1 sub1 on amain.a_id = sub1.a_id");  
        query.addScalar("aId", Hibernate.INTEGER);  
        query.addScalar("name", Hibernate.STRING);  
        query.addScalar("as1Id", Hibernate.INTEGER);  
        query.addScalar("as1Name", Hibernate.STRING);  
        query.setResultTransformer(Transformers.aliasToBean(AFamilyDTO.class));  
 List<AFamilyDTO> list = query.list();  


As I have told in the beginning of the post, there are multiple ways to fetch data in hibernate. So, before you blame hibernate for the performance issues in your application have a look all the options it provides you to fetch the data. Turn on the show sql flag on and see how many queries are getting fired. Then see if you can use any alternative ways of fetching data.