Home

News: Spring Framework 0.9 Released

  1. Spring Framework 0.9 Released (103 messages)

    The Spring Framework project has announced its first release. Spring is a J2EE framework that came out of Rod Johnson's Expert One-on-One book.

    The Spring Framework includes:

    - Powerful IoC-based (Inversion of Control) configuration management, dealing with JavaBean instances. This makes wiring up applications quick and easy, applying one consistent and elegant approach everywhere. No more singletons littered throughout your codebase; no more arbitrary properties files. No need to implement Spring interfaces or special constructors to run your business objects within Spring's lightweight
    container: just use standard, elegant, JavaBeans concepts. The framework is as non-intrusive as possible, allowing for easy testing and maximum reuse of individual beans. Testing Spring applications, and writing them test first, is a breeze.

    - JDBC abstraction layer that makes it a pleasure to query, update, insert and call stored procedures. Spring JDBC offers a meaningful exception hierarchy (no more pulling proprietary codes out of SQLException), simplifies error handling and greatly reduces the amount of code you'll need to write. You'll never need to write another finally block to use JDBC again. Like most parts of the framework, this can be leveraged within Spring but also as individual library. Our automatic exception mapping supports all mainstream databases and is highly extensible. Our data access exception hierarchy is independent of JDBC, and works with our Hibernate and JDO support, so it's ideal for implementing the Data Access Object pattern.

    - Similar abstraction layer for transaction management, making it easy to handle transactions without dealing with low-level issues of a specific transaction API such as JTA. The actual strategy is determined by configuration: SPI implementations are provided, for JTA, for a single JDBC DataSource, for Hibernate and other popular data access patterns. Spring transaction support allows for high-level transaction demarcation in all kinds of environments, including non-JTA ones like Tomcat, test suites, and standalone applications. If your application scales beyond a singledatabase, you'll be able to move from JDBC transaction management to JTA without changing a line of Java code.

    - Integration with Hibernate and JDO, providing the same level of programming convenience as the JDBC support, in terms of both data access and transaction management. In combination with Spring's generic support for transactions and data access objects and exceptions, transactional business objects do not need to be aware of the underlying data access strategy: alternatives such as JDO-only or mixed Hibernate and plain JDBC access are treated consistently.

    - AOP functionality, fully integrated into Spring's configuration management. You can AOP-enable method calls on any object managed by Spring, adding aspects such as declarative transaction management. With Spring's AOP support and transaction abstraction, you can have declarative transaction management without EJB -- even without JTA, if you're using a single database in Tomcat. Spring is committed to supporting the AOP Alliance interfaces, so your AOP interceptors won't be tied to Spring. Equally, Spring's declarative transaction interceptor should soon run in other AOP frameworks.

    - Remoting support, for accessing and exposing remote services in a consistent manner. This allows for handling remote services just like local application beans, using standard business interfaces without remoting dependencies. The actual remoting protocols and even the choice between local and remote beans can be considered configuration details. Concrete implementations are provided for Caucho's Hessian/Burlap web services, and for transparent RMI. Further web services support will be added in future releases.

    - Flexible MVC web application framework, built on core Spring functionality. This framework is highly configurable and as non-intrusive as possible. It offers pluggable handler mapping and view resolution, provides locale and theme support, and elegantly accommodates multiple view technologies. As an alternative, any other web framework (like Struts or WebWork) can be used while still leveraging Spring's middle tier and data access tier support.

    Visit the Spring framework home page:
    http://www.springframework.org

    Download the framework

    Threaded Messages (103)

  2. Spring Framework 0.9 Released[ Go to top ]

    Is Rod planning to update his book to reflect this recent changes in the framework or even writing a book dedicated to the use of Spring?
  3. Spring Framework 0.9 Released[ Go to top ]

    Hey, Rod, there's a first customer if you choose to write a book on Spring! Chances are I'd invest in a copy too....
  4. Spring Framework 0.9 Released[ Go to top ]

    The documentation is very well written especially the tutorial. Frameworks can only be useful if good documentation are available. ;-)

    Well done!
  5. New book?[ Go to top ]

    My next book will certainly refer to Spring, although it won't be purely a book about Spring. It will be another book about J2EE design, using Spring for all the examples.

    Expert One-on-One J2EE Design and Development is still very relevant to Spring as it lays out the basic approach. Although the codebase has evolved significantly through having a true open source community, we've remained faithful to that basic approach.

    Regards,
    Rod
  6. New book?[ Go to top ]

    I can recommend Rod's book to everyone dealing with J2EE, regardless of the current state of the spring framework.
  7. Book[ Go to top ]

    Thanks. Btw, the book is available again from Amazon and elsewhere, after being out of print for a month or two due to Wrox's collapse. Wiley took over the Wrox brand and best selling titles.

    Rod
  8. I can recommend Rod's book to everyone dealing with J2EE, regardless of the current state of the spring framework.


    I wholly agree - but I can also recommend checking out the Spring Framework too, no matter if you've read the book or not :-) Of course, the book and Spring share the same approach and basic design principles - after all, a framework is mainly applied design patterns. So if you agree with the basic design principles outlined in the book, you'll feel very comfortable with Spring. But you can benefit from the applied principles in Spring in any case...

    A major goal of the framework is to stay as non-intrusive and lightweight as possible, so that application code doesn't have to know about being managed by an application container unless absolutely necessary. This follows Rod's principle of not tying application code to a specific framework, to allow for maximum reusability. Spring's bean reference mechanism is a good example: It allows to wire up application beans via Inversion of Control, avoiding the need for any lookups or factories within the bean implementation classes. Thus, any such application bean can be reused outside of a Spring context without hassle.

    Juergen
    Spring Framework developer
  9. Well, I've been checking out Spring this morning and my statement always is: if I don't understand something in half an hour, it's not worth spending more time on it. Well, the concept was totally clear to me in five minutes and it the implementation seems really promising...

    Check it out!
  10. Also note that while the framework offers an array of features, you can choose which parts to use. I've used just the configuration framework on two projects without using any other part of the framework and got great results from it. And it is very non-intrusive - only had to import a Spring API in one class.

    Rob
  11. Non-intrusiveness[ Go to top ]

    Yup, I just found that out! The way decoupling is handled on all sides is really nice! I always thought it was strange to write ActionForms for every data object you want to create and edit via the web when I was Struts. Right now I just edit the DAO's themselves! For more complex properties (e.g. java.util.Dates but also proprietary types), you just use one of the PropertyEditors (part of java.beans) that are part of Spring or you create your own. And it changes nothing to your data classes!
  12. Non-intrusiveness[ Go to top ]

    I have just started to use the configuration management capabilites in my current project.Everything works smoothly so far.Very easy to use it,test it and quite powerfull with the possibilities to reference beans as variables
    for the definitions of beans.

    The only missing information if I am not mistaken is the list of jar files
    needed to recompile the source code. The distribution comes with some of them
    but not all of them.

    Thx,Claude
  13. Non-intrusiveness[ Go to top ]

    The only missing information if I am not mistaken is the list of jar files

    > needed to recompile the source code. The distribution comes with some of them
    > but not all of them.

    This is correct. Spring has quite a lot of dependencies on third party libraries, like Hibernate, JDO, Hessian/Burlap, Velocity, etc (~ 9 MB libraries in total). The Spring sources are mainly included for documentation purposes, not for rebuilding.

    You're invited to use a full CVS snapshot if you'd like to build Spring yourself :-) If you just want to enrich your distribution for building, try to grab all the stuff from /main/lib in CVS, and build.xml + build.properties from /main.

    Juergen
  14. Non-intrusiveness[ Go to top ]

    BTW, there's a new article on "lightweight containers" available in the Spring documentation section, highlighting the advantages of non-intrusive IoC, and comparing Spring's bean-based approach to PicoContainer's constructor-based one.
  15. Looking Good[ Go to top ]

    An excellent framework… I’ve been following the development of the framework since reading the book. I especially like the lightweight feel to it.
     
    Spring has moved on from the framework presented in the book with new features like AOP. I would, however, be interested in knowing how the original framework has changed – i.e. where the book is now out-of-date.

    On a general note Spring, as with many other frameworks, depends on configuration files (a combination of XML and property files). This gives great flexibility but at the expense of a certain degree of static type and variable checking. Is the only solution to this tool support or relying on testing to uncover problems?
  16. Looking Good[ Go to top ]

    With the config framework, you do at least get the benefit of the framework bombing out if anything is wrong in the configuration. So if the configuration is loaded as part of a servlet that is immediately initialized, or perhaps as part of a test case, you'll know immediately that something's wrong and/or misconfigured. This is at least better than not knowing about the misconfiguration until the part that it affects is tested.

    Rob
  17. Looking Good[ Go to top ]

    Spring has moved on from the framework presented in the book with new features like AOP. I would, however, be interested in knowing how the original framework has changed – i.e. where the book is now out-of-date.


    There have been some package moves and class renames (such as ControllerServlet -> DispatcherServlet). Also the XML bean factory format has changed to allow better validation, although it's still clearly recognizable from the book. And there have been countless incremental improvements.

    Thus the book is still a great resource for the basic approach, but don't try typing in the XML examples in particular in the current version. The AOP support is new, as is the transaction infrastructure. There have been significant enhancements to the MVC framework, although they're mostly backward compatible. JDBC has also improved significantly (with automatic exception mapping in all mainstream databases); however, the concepts are still as described in Chapter 9.

    I should probably write a document listing some of the differences and put it on the Spring web site. However, the book is a book about J2EE design that happens to introduce a framework and use it for examples. It's not a book about the framework itself. The fact that the framework now has a thriving open source community behind it (and is being used for real projects) tends to validate the design approach the book advocates, even if it renders some of the examples obsolete.
      
    > On a general note Spring, as with many other frameworks, depends on configuration files (a combination of XML and property files). This gives great flexibility but at the expense of a certain degree of static type and variable checking. Is the only solution to this tool support or relying on testing to uncover problems?
    Interesting point. As you say, the issues are similar to those in Struts or the many other frameworks that rely on XML metadata. (Note that Spring is perhaps unique in that it doesn't depend purely on XML. It so happens that the XML and properties bean definition formats are most often used, but as the BeanFactory itself is an interface with a storage-independent abstract implementation providing common behaviour, Spring can easily accommodate storing configuration in the database, LDAP etc.)

    I'm a firm believer in strong testing, as you'll know from my book. (Bruce Eckel has an interesting article on "Strong typing vs strong testing".) However, it's important to remember that because Spring suports inversion of control, few application need to cast objects from a bean factory, so there's little reason to sacrifice type safety. For example, if you write a Spring MVC web app using IoC, you can have strongly typed JavaBean properties on all your business objects and won't need any type casts.

    From the early versions, I made an effort to ensure that failures due to invalid XML configuration (such as setting references to the wrong type) produce clear error messages.

    Thanks for your comments,
    Rod
  18. Looking Good[ Go to top ]

    "few application need to cast objects from a bean factory" : oops, I meant "few application objects"
  19. AOP and JDO[ Go to top ]

    Ok, the comments here are extremely motivating. I will put Spring high on my list of things to do.

    However something else, but related, is interesting me. Much has been said about AOP. This is a topic which intrigues me but in which I have no experience. I'd like to know if the community believes there is application of AOP to JDO. Would the introduction of plug-in points (pointcuts in AOP speak?) to the JDO architecture be beneficial? Are there any obviously useful places where such plug-in points should be provided? Are there specific use cases which are more easily addressed by the application of AOP to object persistence and O/R mapping?

    Apologies for so many questions in one post. I look forward to any responses, and RTFM may be entirely appropriate!

    Kind regards, Robin.
  20. AOP and JDO[ Go to top ]

    Robin,

    > I'd like to know if the community believes there is application of AOP to JDO. Would the introduction of plug-in points (pointcuts in AOP speak?) to the JDO architecture be beneficial? Are there any obviously useful places where such plug-in points should be provided? Are there specific use cases which are more easily addressed by the application of AOP to object persistence and O/R mapping?
    >

    I'd say that pointcuts to control transactions, caching and lazy loading would be pretty cool. I know Juergen has implemented transaction control in Spring that works with bith Hibernate and JDO.

    Thomas
  21. Practical applications for Spring[ Go to top ]

    I'll like to begin with saying I enjoyed the book. During another thread, you mentioned it and I picked up a copy. The two immediate benefits that paid off was the exception discussion and your Spring based reflection factory(the cut down one). Both gave me immediate benefits after about 20 minutes of reading and paid for the book many times over.

    Thanks!

    Now, my question. I'm working on a J2EE project(of course) and we are using Toplink for the persistence layer. This is a requirement because we are a sub on a contract. My goal is the introduce Hibernate on our next project. Now, can the Spring framework be used to easily wrap and unify different perisitence technologies and provide a consistent way to handle persistence. For example, if I use Toplink now, and Hibernate later, can Spring bootstrap an effort to make them look identical?
  22. Hi David,

    > Now, my question. I'm working on a J2EE project(of course) and we are using Toplink for the persistence layer. This is a requirement because we are a sub on a contract. My goal is the introduce Hibernate on our next project. Now, can the Spring framework be used to easily wrap and unify different perisitence technologies and provide a consistent way to handle persistence. For example, if I use Toplink now, and Hibernate later, can Spring bootstrap an effort to make them look identical?

    I can't express how glad I am to get your pragmatic question after all that exception dissection stuff... ;-) Kudos to you!

    Spring offers all mechanisms that are necessary for abstracting data access and transaction strategies. Business code can simply demarcate abstract high-level transactions, and delegate to data access objects with tool-agnostic interfaces. As the exceptions (*sigh* but I have to mention them) are part of the API contract for both the transaction control and the data access objects, Spring standardizes them in a tool-agnostic way.

    Spring includes concrete transaction management SPI implementations for JTA, a single JDBC DataSource, a single Hibernate SessionFactory, and a single JDO PersistenceManagerFactory. This means that you can scale from such "simple" implementations like DataSourceTransactionManager to the more flexible but container-dependent JtaTransactionManager by simply changing Spring configuration. The nice thing is that you only need to that if you are actually facing distributed transactions for certain deployments of your application - a JTA-capable container is required then, but only then.

    For DAO implementations, Spring provides various kinds of support classes. One approach that it offers for JDBC, Hibernate, and JDO is IoC-style templating with callback implementations, for proper resource handling that the application code doesn't have to care about. These support classes also care for automatically taking part in transactions. An alternative to that programming style is a respective AOP interceptor, delivering similar conveniences.

    For general information on these things, have a look at my "Data Access and Transaction Abstraction" article in the documentation section of the Spring website. A version of the article is also available in the community area of the Hibernate website.

    Regarding TopLink in particular: This is indeed an interesting issue, and it has been floating around for quite a while in various flavors. Both a TopLink transaction manager and support classes like a data access template and an interceptor should be straightforward to implement. As a start, there are very similar implementations available for Hibernate and JDO, and a transaction manager base class that cares for the common transaction workflow issues. I'd estimate no more than 2 days for an initial version of such TopLink support, at least if leveraging some help from the Spring team :-)

    So using this approach, your business objects and thus your UI objects won't depend on a particular transaction, resource acquisition, or persistence strategy. The former two allow for reuse across a wide variety of scenarios, from test environments and standalone applications to J2EE containers, using the same persistence tool. The latter will help to minimize a porting effort from one persistence strategy to another, as far as possible.

    In your particular case, you'll simply have to switch your DAO implementations from TopLink ones to Hibernate ones, and configure a different transaction manager (or stick to JTA for both). The goal here is to keep the DAO interfaces as generic as possible, but without sacrificing performance optimizations that the respective tool offers. And for complex query requests that go into your DAOs as parameters, you can use a custom strategy liked tool-agnostic named queries or the like.

    I hope that helps,

    Juergen

    P.S.:
    For intense discussions of this subject, I invite you to join a Spring mailing list. There isn't so much noise there ;-)
  23. TopLink[ Go to top ]

    I might get some mileage out of TopLink integration myself, at present, so I'd be interested in discussing your requirements. The only unique TopLink issues appear to relate to TopLink's cloning of transactional objects. This may be a bit of an obstacle to transparent persistence, but is a TopLink thing rather than a Spring thing. I think Spring could take you a long way to abstracting TopLink.

    Regards,
    Rod
  24. Well, I've been checking out Spring this morning and my statement always is: if I don't understand something in half an hour, it's not worth spending more time on it. Well, the concept was totally clear to me in five minutes and it the implementation seems really promising...

    >
    > Check it out!

    Could not agree more. That is what attracted me to this framework in the first place, after reading about the JDBC abstraction layer in Rod's book. It has helped me solve a common problem - the leaked connections. Even if you understand JDBC, and you know that you should close your connections - it's always easy to make a misstake, causing you to spend hours tracking down the source of a connection leak.

    I used the code, from the book, that implements a StoredProcedure wrapper object around JDBC CallableStatement. This allowed me to just pass in the sql statement, set the parameter values and then call execute. No need to open and close connections. No need to catch exceptions, since they are translated to RuntimeException, unless I think I can actually recover (unlikely in my case).

    I have since then joined the Spring project in order to help adding some new functionality to the JDBC framework.
  25. <Thomas>
    No need to open and close connections. No need to catch exceptions, since they are translated to RuntimeException, unless I think I can actually recover (unlikely in my case).
    </Thomas>
     
    This is a particular feature that I would strongly disagree with. Framework that converts exceptions into RuntimeException virtually imposes a restriction on any potential user that all exceptions are unrecoverable. I have heard all the arguments made by Rod about checking Javadoc and from personal experience with C# can testify that this approach does not scale. It makes creating robust applications a much more difficult task since in runtime-exception world unless developer catches java.lang.RuntimeException there is no 100% guarantee that all exceptions are properly handled.
     
    I have no intention of starting another checked/unchecked exceptions flaming thread and am merely expressing my personal disappointment in regard to exception handling within the framework. I believe that by trying to save on a few try/catch or throw clauses we unknowingly create a C#-like environment where no exception can be statically checked at compile time. The only answer I have heard from Microsoft in this regard is "check the documentation". C# library itself proves that this strategy is not robust, since in many places C# library methods themselves throw undocumented exceptions.
     
    As far as Spring Framework, developers did a nice job of documenting all exceptions, but if along with Spring I use other libraries/frameworks with similar exception handling strategy, I am forced to go an extra mile in my attempt to document all explicitly or implicitly thrown exceptions for all methods within my code and undoubtedly making mistakes along the way.
     
    This is just my opinion and in no way it is a reflection on overall quality of Spring Framework which I am sure is outstanding. I am just regretful that developers that share my opinion will be unwillingly forced to deal with flawed design of excessive overuse of runtime exceptions within frameworks or libraries.

    Regards,
    Dmitriy Setrakyan
    Fitech Labs, Inc.
    xNova™ - Service Oriented Architecture for Java and .NET
  26. Getting a little off topic here. I think the use of RuntimeException in web applications is very useful.

    When planning an application error/exception handling strategy we need to plan for the different types of errors which can occurs in our application:

    1. System errors (InternalError, VirtualMachineError) which you cant do anything about, and you shouldn't try to deal with. These should never occur in production.

    2. Programmer errors (NullPoinerException, IllegalArguementException, IllegalArguementException, StackOverflowError) which should be identified in unit and system testing. You also shouldn't try and catch with these, let them bubble up and show you where the bug is. These should never occur in production.

    3. Application errors (SQLException, IOException) which may occur in production. These are the errors which we need to handle in our application.

    Now we are getting into to the trickier area. After many years of experience, my opinion is that if you resources which you need to free (Connection, InputStream, etc) you should use a checked exception so the calling code is forced to deal with it and free the resource.

    In other cases your code should ensure no errors occur, so exception handling is not required. For example a method public void List getCustomers() should return an empty list (Collections.EMPTY_LIST) rather than throwing a checked ObjectNotFoundException.

    When a method has to catch a checked exception which it can do nothing about and should not occur (e.g. ClassNotFoundException due to a configuration error) I would throw an ApplicationException (which would extend RuntimeException) and set the cause to be the checked exception.

    Now we need a top level application Exception handler which can be switched between development and production mode, displaying the appropriate information.

    Using this strategy you will greatly reduce the amount exception handling code you have to write.
  27. I also have no desire to get into the checked/unchecked debate in detail. But I'll echo Dmitriy and say that I find overuse of unchecked exceptions an unscalable approach from a maintenance and correctness point of view. And I'll go further and say that try...catch blocks aren't a nuisance you should be thinking about factoring out of your code. Instead, they're a tremendous help in ensuring code correctness - just like plain old static typing. It's just my experience alone, but based on that experience unchecked exceptions cause some of the biggest headaches when it all hits the fan and you're trying to sort out a production problem.

         -Mike
  28. Mike,

    > I also have no desire to get into the checked/unchecked debate in detail. But I'll echo Dmitriy and say that I find overuse of unchecked exceptions an unscalable approach from a maintenance and correctness point of view. And I'll go further and say that try...catch blocks aren't a nuisance you should be thinking about factoring out of your code. Instead, they're a tremendous help in ensuring code correctness - just like plain old static typing. It's just my experience alone, but based on that experience unchecked exceptions cause some of the biggest headaches when it all hits the fan and you're trying to sort out a production problem.
    >

    From my point of view, the use of checked exceptions by themselves hardly ensure correctness. You would need some other mechanism for that - I have seen a lot of exceptions caught without beeing handled properly - maybe not even handled at all - empty catch block works pretty well :-). So if you have another mechanism for ensuring correctness, maybe it could be extended to cover any unchecked exceptions that you deem necessary to handle. Just a thought.

    Regards,

    Thomas
  29. \Thomas Risberg\
    From my point of view, the use of checked exceptions by themselves hardly ensure correctness. You would need some other mechanism for that - I have seen a lot of exceptions caught without beeing handled properly - maybe not even handled at all - empty catch block works pretty well :-). So if you have another mechanism for ensuring correctness, maybe it could be extended to cover any unchecked exceptions that you deem necessary to handle. Just a thought.
    \Thomas Risberg\

    As I said, they _help_ ensure correctness. They don't guarantee it.

    And the difference is one of knowledge and explicitness. A person who creates an empty try...catch block does so explicitly, often when the compiler complains to them. That's obviously a reflex created out of a desire not to know what's going on.

    Either way, a developer has to write code to deal with it, even if it's incorrect.

    Unchecked exceptions are entirely different. Under a burden of many frameworks, lots of code, or just slipping up occasionally, a developer who is very conscientious and very keenly interested in handling exceptions a certain way can very, very easily miss an unchecked exception.

    And this leads to my point on production problems. It's one thing if a compiler warns me about something and I take an irresponsible out. It's another thing entirely if I have no programmatic way of determine what the correct action is.

    In fact, the tone of your response sounds entirely reasonable if you think of one call scrutinized to death in a technical forum. It's an entirely different matter when you consider an enterprise application with tens or hundreds of thousands of lines of code. Factor in the fact that unit tests are notororiously bad at testing hard failure conditions (like lock contention), and you've created an environment where it's all too likely that an error will slip into production code unnoticed.

    To be perfectly blunt, the approach you're advocating smells an awful lot like an old C-based system where return codes are routinely ignored - and part of the reason why exceptions were created in the first place. Perhaps if you're called in at 2am to diagnose one or two of these types of problems you might be more inclined to fall less on the side of saving some try...catch code, and more on trying to make sure you're _not_ called at 2am in the first place.

        -Mike
  30. Ouch![ Go to top ]

    com.interface21.dao.OptimisticLockingFailureException is a subclass of java.lang.RuntimeException? Ouch!
     
    It would be interesting to find out a rational around this design decision. I assume that optimistic lock failure happens when multiple updates and, in some data stores, reads and updates within different transactions cannot be serialized. Extremely common scenario which often pops up in production. Moreover, in majority of cases optimistic lock failures will require non-generic explicit recovery process that may vary per every transactional unit of work. In short, depending on business transaction, business logic will to the least either retry or deliver a specialized error message to the user.
     
    So, why use unchecked exception for scenario that is indeed recoverable and needs to be handled almost in all cases for any application? Why not force the user to handle it? Is the rational behind it to claim that optimistic lock failures are unrecoverable? Or is it a bug to be fixed in the next version?

    Kind regards,
    Dmitriy Setrakyan
    Fitech Labs, Inc.
    xNova™ - Service Oriented Architecture for Java and .NET
  31. Ouch![ Go to top ]

    Dmitriy,

    > com.interface21.dao.OptimisticLockingFailureException is a subclass of java.lang.RuntimeException? Ouch!
    >
    > So, why use unchecked exception for scenario that is indeed recoverable and needs to be handled almost in all cases for any application? Why not force the user to handle it? Is the rational behind it to claim that optimistic lock failures are unrecoverable? Or is it a bug to be fixed in the next version?
    >

    I don't think that we are implying that optimistic lock failures are unrecoverable :-). I would defenitely encourage anybody to catch this exception and handle it - but only if they expect their use of the framework to potentially throw this kind of error. I wouldn't want to force everybody using the framework to use a try-catch block for some exception that would never be thrown in their environment.

    We had to pick one way of handling all different types of excpetions thrown during data access, and to be consistent we decided to handle all of them the same way. Singling out a subset and forcing the developers to catch them would kind of defeat our original approach.

    Now, you may disagree with our decision to use unchecked exceptions, but I would argue that consistency is even more important than controlling whether the developer handles all excpetions or not.

    Regards,

    Thomas
  32. Ouch![ Go to top ]

    \Thomas Risberg\
    Now, you may disagree with our decision to use unchecked exceptions, but I would argue that consistency is even more important than controlling whether the developer handles all excpetions or not.
    \Thomas Risberg\

    This sort of consistency generally translates into "elegance" of the interface and API. To create a break for special situations can make the API more unwieldly.

    This is, IMHO, why so many truly battle-tested, tried and true APIs may not look very pretty, but work very, very well under heavy stress production situations. There's often a strong temptation to go for elegance, but the universe at large is rarely accomodating to that approach in the long run.

    In short, complex applications (and their solutions) can have a core of breath taking elegance, but they also need to make concessions to reality.

        -Mike
  33. Ouch![ Go to top ]

    If get to carried away with checked exceptions you will end up with an EJB like API and everytime you do something you will need wrap it in a try/catch block.

    There seems to be an emerging thread that heavy stress production situations (real systems) require checked exceptions. Well there are two points I would like to make here:

    1. Using exceptions for normal application control should be avoided, its very CPU expensive.

    2. Most of the mission critical system we use every day, such as the aircraft flight control system, are written in Ada83 which only provides unchecked exceptions.
  34. Ouch![ Go to top ]

    \Malcolm Edgar\
    If get to carried away with checked exceptions you will end up with an EJB like API and everytime you do something you will need wrap it in a try/catch block.
    \Malcolm Edgar\

    No, this is a _very_ common misstatement. The majority of the time, adding a "throws ..." statement is sufficient. If you wish to be truly easy-going about it, you can say "throws Exception".

    I suppose you find even this two-words tacked on a method onerous in your designs?

    Secondly - when accessing a potentially remote object, don't you think you should consider the fact that the remote access should fail? Explicitly? Your post seems to be indicating that catching exceptions is _such_ a bother that we should avoid it when possible. Personally, I find the throws or try...catch code counts _wildly_ overstated by people who just don't like dealing with errors very often. In fact, a vocal minority seems offended that they have to deal with errors at all.
     
    \Malcolm Edgar\
    1. Using exceptions for normal application control should be avoided, its very CPU expensive.
    \Malcolm Edgar\

    Agreed, but this doesn't tie back to your EJB comment at all. Or do you consider a RemoteException to be common? :-)

    \Malcolm Edgar\
    2. Most of the mission critical system we use every day, such as the aircraft flight control system, are written in Ada83 which only provides unchecked exceptions.
    \Malcolm Edgar\

    Most? I humbly disagree. Ada is most often used in mandated government contracts, and you will not hear about it outside of government circles very often (if at all). It is also the primary example of language-design-by-committee. Can we keep the discussion on languages that at least 15% or so of developers here are likely to know?

    And if you wish to talk of truly real time critical systems, like it or not most of them are still done on C or assembler under a real time operating system. Ada is a forth-or-fifth ran at best.

       -Mike
  35. Ouch![ Go to top ]

    Ok replace "Most" with "Many". Now your point is?

    Aside:
    Boeing and Airbus use Ada for their safety-critical systems, I am not talking about a time-critical wristwatch.

    Ada83 was design by the French Honeywell-Bull team in response to a US DOD competition, their entry was then selected by a committee.
  36. Ouch![ Go to top ]

    I totally disagreed with Rod's decision, but used the framework anyway because it offered so many other benefits. Having developed without checked exceptions for over 3 months now, and dealing with those "2 AM phone calls" for the past month, I have reversed my opinion. Unchecked exceptions are great provided they are backed by good documentation (which Spring provides) and solid testing (which is my problem). I can catch any unchecked exception I want and ignore those I don't. Previously, I had to catch those I didn't want. In a competitive market where contracts are won and lost based on budgets and deadlines, an extra try catch here and there (and there ... and there) really adds up, even if it is only 2 words (duplicated thousands of times).
  37. Exception hierarchies[ Go to top ]

    <quote>
    I can catch any unchecked exception I want and ignore those I don't.
    </quote>
    I think this is a key point. Unchecked exceptions don't equate to "no exception handling." To make the choice of what to catch useful, Spring JDBC provides a meaningful exception hierarchy. So it's possible to catch just, say, DataResourceFailureException if you're (unusually) able to try another database if you can't connect. Compare this with JDBC: pretty much one checked exception (SQLException) for everything, which leaves you digging into non-standard vendor error codes to get beyond just knowing that "something went wrong". Typically you're only interested in recovering one scenario (if any), but you have to do quite a bit of work to establish what scenario you're actually looking at.

    Regards,
    Rod
  38. Exception hierarchies[ Go to top ]

    Let's not forget that JDO models its exception in a very similar fashion: JDOException extends RuntimeException, JDOCanRetryException extends JDOException - no checked exceptions at all. The JDO designers obviously consider this a viable decision for higher-level APIs, and I do too. I can understand that low-level APIs throw checked exceptions for a lot of cases, but higher tiers of an application shoudn't _have_ to worry about such details of lower tiers. Especially if framework mechanisms care for proper resource and transaction handling as far as possible, like with Spring.

    Again, you can always catch certain exceptions that you're interested in handling, but you're not forced to, especially if particular exceptions may not be applicable at all. If you don't use optimistic transactions, why _have_ to catch a OptimisticLockingFailureException in all locations where it might possibly occur? The surfacing of such failures can be dependent on the actual flushing strategy, e.g. with Hiberate, so it could potentially get thrown by every piece of data access code, but also on transaction commits. Do you really want to be _forced_ to deal with this in all such locations, no matter if your particular strategy will use optimistic exceptions at all?

    FYI, see also Bruce Eckel's discussion on exceptions here.

    Juergen
  39. Exception hierarchies[ Go to top ]

    <juergen>
    Let's not forget that JDO models its exception in a very similar fashion...
    ...
    FYI, see also Bruce Eckel's discussion on exceptions here.
    </juergen>
    JDO adopted runtime exception mainly b/c of runtime code augmentation (as one of the main implementation venue). Checked exception simply won’t work there.

    As far as Bruce Eckel’s comments, they were ridiculed countless times already so I won’t repeat it here…

    Regards,
    Nikita Ivanov.
    Fitech Labs.
  40. Exception hierarchies[ Go to top ]

    Nikita,

    > JDO adopted runtime exception mainly b/c of runtime code augmentation (as one of the main implementation venue). Checked exception simply won&#8217;t work there.

    <jdo-spec>
    The exception philosophy of JDO is to treat all exceptions as runtime exceptions. This preserves the transparency of the interface to the degree possible, allowing the user to choose to catch specific exceptions only when required by the application.

    JDO implementations will often be built as layers on an underlying data store interface, which itself might use a layered protocol to another tier. Therefore, there are many opportunities for components to fail that are not under the control of the application.
    </jdo-spec>

    So this isn't entirely an implementation issue but an API design decision too. And the latter argument on various underlying datastores that the application shouldn't be confronted with applies to generic DAO interfaces too, which Spring's DataAccessException hierarchy is a part of. Spring provides out-of-the-box support for such DAOs built on top of JDBC, Hibernate, and JDO.

    > As far as Bruce Eckel&#8217;s comments, they were ridiculed countless times already so I won&#8217;t repeat it here&#8230;

    I won't argue on the value of Bruce Eckel's statements here, although I have my personal opinion. Let me just state that I don't agree with everything he says: For example, I don't like the ExceptionWrapper idea, I prefer clean API-level exception hierarchies. Your mileage may vary, but please accept that your view isn't the only viable one in the software industry.

    Juergen
  41. Exception hierarchies[ Go to top ]

    Hi Juergen,
    You reminded me Eckel’s comments and I would like to post one of the replies to them (clearly colorful but nonetheless):

    ******************************
    I can't believe this article or that so many people agree with it.

    It is saying... (and if you don't think it is please tell me why)

    "Programmer shouldn't be forced to write robust high quality code because it's extra work that they will subversively avoid in order to get the job done. And! on large projects it's too hard to get the code written if the programmers have to handle errors properly. It's better to allow programmers to write lots of poor quality code quickly to meet their development schedules and hope that bugs are caught at some stage in debugging."

    I find this is unbelievable. Programmers who'd rather not write exception safe classes with enforced interfaces, complete exception handling, and determinate state, should be fired, just like programmers who don't want to test their code.

    C++ (I've been writing it professionally for the last ten years) makes it easy to write so many different types of bugs and not enforcing exception specs is one of the big ones - especially in large distributed projects using CORBA!
    I love C# but this is a big oversight. I hope and expect that the CSharp and CLR Teams' reasons for not enforcing exception specification are a lot better than those described in this article.

    Baffled,
    Nev Delap
    Nev dot Delap at Australia dot Boeing dot com
    ******************************

    Granted, properly using checked exception and *understand* them from system design and architecture standpoints requires more than just average IQ but it’s certainly not a rocket science. Professional incompetence and just simple laziness are lame excuses for poor engineering practice.

    Some of the people of the Eckel’s discussion hacked the javac to stop checking for checked exception so their lives would be easier... It is startling that people can be so brainwashed on the technical subject and completly loose the grip on reality of their work.

    Despite my disagreement I appreciate this discussion,
    Nikita Ivanov.
    Fitech Labs.
  42. Exception hierarchies[ Go to top ]

    I'm not sure that selectively quoting from the replies to Bruce Eckel's comments gets us far. I could equally quote from those who strongly supported him. Maybe we should just compromise on a set of links? (Although as I said, this is probably the wrong thread: why don't we revive one of the threads devoted to this discussion, reread it and see what we think we can add that's new.)

    I'm amazed at how much heat this issue generates. I used to use checked exceptions exclusively, for my first 5 or so years of programming in Java. I did a lot of thinking on the issue and changed my views. (Note that I don't advocate exclusive use of unchecked exceptions.) Although my conversion was independent, I subsequently learnt that Bruce Eckel and Martin Fowler among others had come to similar conclusions. I have used mainly unchecked exceptions in several projects and am very pleased with the results. I don't believe I deserve to be fired, that I'm lazy (I couldn't have written a 700-page book if I was lazy :-) or ignorant. I just differ from your opinion, and that's fine.

    One more quote and I'm done. From the rationale for the decision not to go with checked exceptions in C#:

    "Examination of small programs leads to the conclusion that
    requiring exception specifications could both enhance developer productivity
    and enhance code quality, but experience with large software projects
    suggests a different result -- decreased productivity and little or no
    increase in code quality."

    This is my experience as well. I have seen far more problems caused by swallowing checked exceptions (silent failure, probably not even logged) than by overuse of unchecked exceptions.

    I don't think it's correct to assume that programmers won't ever catch unchecked exceptions. Lazy programmers who really don't bother to understand the code they use may do this, but these are the programmers who will simply subvert the intent of any checked exceptions they encounter by writing catch Exception(ex ) {}. There are a minority of people who will write bad code no matter how hard you try to prevent them.

    Regards,
    Rod
  43. Exception hierarchies[ Go to top ]

    I don't think it's correct to assume that programmers won't ever catch unchecked exceptions. Lazy programmers who really don't bother to understand the code they use may do this, but these are the programmers who will simply subvert the intent of any checked exceptions they encounter by writing catch Exception(ex ) {}. There are a minority of people who will write bad code no matter how hard you try to prevent them.

    My distaste for unchecked exceptions has come after almost 10 years of VB experience (I've switched to Java but still have MS clients). I don't know of any other way to know know what unchecked exceptions might be thrown other than to look at the code (how far do I gotta dig? + do I have the source?), the documentation (always accurate :) + how far do I gotta dig?) and experience(when it blows up in production or whenever). So developers end up protecting themselves (one might call this lazy) by this "catch (Exception e)" at the beginning of the "program" or in every method. (VB it looks like "On Error Goto 0 If err.number != 0 Then"). Ugh.

    At least with checked exceptions, i can run something that will look for buried exceptions. Guess what happens in C# (or any .Net language) when I code my data access to inteface and then allow my customer to choose their database and they don't choose any I've tested with and I didn't do a generic catch?

    I think real the rational for not using checked exceptions in C# (.Net) was because it probably wouldn't work with the myriad of languages that are used within .Net. (no proof just cirumstantial)

    That said, give me some links (other than C# rational) that give me good reasons why I should use unchecked exceptions. I hear alot of talk(ie "unchecked is better" but no real proof (ie "Lazy programmers just bury checked exceptions)". I am always willing to learn so learn me. :) Sorry to continue with this. but I would like to know. Just some links would do.
  44. Exception hierarchies[ Go to top ]

    I think real the rational for not using checked exceptions in C# (.Net) was >because it probably wouldn't work with the myriad of languages that are used within .Net. (no proof just cirumstantial)

    >

     It is not a problem for .NET. It is a JAVA compiler "feature" not JVM. All exceptions are unchecked for both JVM and CLI.

    > That said, give me some links (other than C# rational) that give me
    >good reasons why I should use unchecked exceptions.

    > I hear alot of talk(ie "unchecked is better" but no real proof
    (ie "Lazy
    >programmers just bury checked exceptions)". I am always willing to
    learn so
    >learn me. :) Sorry to continue with this. but I would like to know.
    > Just some links would do.

    http://www.mindview.net/Etc/Discussions/CheckedExceptions
    by Bruce Eckel, the author of "Thinking in Java".
  45. Exception hierarchies[ Go to top ]

    It is not a problem for .NET. It is a JAVA compiler "feature" not JVM. All exceptions are unchecked for both JVM and CLI.

    So theoretically, one could create a good :) .Net compiler.

    http://www.mindview.net/Etc/Discussions/CheckedExceptions
     by Bruce Eckel, the author of "Thinking in Java".


    Much Grass (thanks!). I will check it out.

    Now, back on topic. What was it?
  46. Exception hierarchies[ Go to top ]

    Juozas: It is not a problem for .NET. It is a JAVA compiler "feature" not JVM. All exceptions are unchecked for both JVM and CLI.

    The JVM 1.02 spec states:

    A method should only throw an exception if at least one of the following three criteria is met:

        * The exception is an instance of RuntimeException or one of its subclasses.
        * The exception is an instance of Error or one of its subclasses.
        * The exception is an instance of one of the exception classes specified in the exception_index_table above, or one of their subclasses.

    The above requirements are not currently enforced by the Java Virtual Machine; they are only enforced at compile time. Future versions of the Java language may require more rigorous checking of throws clauses when classes are verified.


    The 1.2 spec actually relaxed the wording:

    These requirements are not enforced in the Java virtual machine; they are enforced only at compile time.

    I found that very interesting ...

    Peace,

    Cameron Purdy
    Tangosol, Inc.
    Coherence: Easily share live data across a cluster!
  47. Exception hierarchies[ Go to top ]

    Mark, there's also discussion of my views on exception handling in part of chapter 4 of my book, available online.
  48. Exception hierarchies[ Go to top ]

    Mark, there's also discussion of my views on exception handling in part of chapter 4 of my book, available online.
    Thanks - I'll check it out. I looked at the other link and it provided nothing substantial.
  49. Re: Rod's comments[ Go to top ]

    Hi Rod,
    I will keep typing away :-)

    There were questions as to applicability of this discussion to the topic of this thread. I strongly believe that error handling (and hence exception handling) is the fundamental part of any software system, very much so in general purpose frameworks that serve as foundation for other layers of software. So, I think this discussion is very relevant to whether Spring framework’s design is flawed or not.

    As far as C# team’s comment it’s an almost known fact that they have chosen it primarily because introducing checked exceptions would erect a huge barrier for the millions of VB developers whose migration to C# or VB.NET (that share the same SDK APIs) is viewed as critical for .NET success. Also, Hejlsberg never understood checked exception in the first place (he’s from Borland; look at Delphi). Furthermore, it was pointed many times that these comments are unsubstantiated: where is the research, the paper, etc that explains this “experiment” they are quoting, how it was conducted, etc.

    The only large enough to be statistically worthy “experiment” that I’m aware of is C++ with its unchecked exceptions mechanisms. No comments required there, I guess...

    Coupe of more comments.

    Many readers suggested that the main reason to use unchecked exception is to simplify the code and get rid of those pesky and annoying try-catch blocks. Sure, using runtime exception can reduce number characters one has to type on the keyboard to produce compilable piece of code. However, if you think that software engineering is all about reducing the number of lines you type – you’re thoroughly misled and you should probably consider the change of your occupation.

    Another interesting myth is that unchecked exception allow user to catch exceptions selectively (thus potentially simplifying the error handling code), i.e. only those the user knows will be thrown and he/she can handle, and to ignore rest of them using some sort of global catch for such ignored exceptions. Well, such “selectivity” among many other things basically means that user must be fully aware of the underline code implementation thus incurring extreme coupling. Funny enough, this argument goes along with the argument of making all private variables public to allow users “optimize” or “simplify” their use of such class – indeed, code will still compile, it will be probably shorter, no more of those pesky public getters/setters; I’ve met people who seriously argued that this technique is great b/c it gives a significant performance boost :-) …

    But probably most simple to understand and yet very powerful argument in favor of intelligent usage of checked exceptions is: there is no way to know what unchecked exception to catch or expect in any given point of program unless you either 100% rely on documentation or traverse the entire call graph in source code. Needless to say that both assumptions are deeply flawed in the real life. For frameworks alone with miniscule size such as Spring the documentation issue may not be as critical but for other applications that are built on top of this framework the both points might become fatal pretty soon.

    Best regards,
    Nikita Ivanov.
    Fitech Labs.
  50. Re: Rod's comments[ Go to top ]

    <Nikata>
    Many readers suggested that the main reason to use unchecked exception is to simplify the code and get rid of those pesky and annoying try-catch blocks. Sure, using runtime exception can reduce number characters one has to type on the keyboard to produce compilable piece of code. However, if you think that software engineering is all about reducing the number of lines you type – you’re thoroughly misled and you should probably consider the change of your occupation.
    </Nikita>

    This is a great way to prove a point. Some doesn't agree, therefore, they are lazy, ignorant, and now in the wrong profession. I read about the checked/unchecked debate and tried putting the emphasis on unchecked rather than checked exceptions in order to arrive at my own conclusion.

    I agree that it is cleaner and more understandable and neither of my reasons for agreeing have anything to do with how much I'm typing. In addition, I've been doing this for a while and even after this switch, I am quite convinced that I'll be doing this for some time to come.

    If you don't care for this particular architectural decision, could you please TRY to coach your reasons in terms of Spring and TRY to avoid insulting the people who have managed to work in their chosen careers successfully, for years, without the benefit of your guiding light?
  51. Re: Rod's comments[ Go to top ]

    Hi David,
    My comments stay put.

    If you argue unchecked exception with reduced number line argument – you are having a very serious misunderstanding about software development. So, you are not one of them – great. I didn’t mean anything personally to anyone – I even asked Rod to sign his book at TSS2003 :-)

    In case you have not noticed my explanations – they are in bold two posts above (as well as some in regular font couple of more paragraphs up in the same post).

    Enjoy,
    Nikita Ivanov.
    Fitech Labs.
  52. Re: Rod's comments[ Go to top ]

    They have to stay put unless someone from TSS removes them. :-)

    I read your posts. I've read off them them in this thread. I've read them all in that other thread, too.

    I don't agree with you. The Spring guys don't agree with you. The JDO guys(according to what I've read, I haven't used JDO myself) don't agree.

    However, the JDBC guys do, as do the EJB guys and some others. Fine. All I'm asking is that since this point has been beaten to death and nothing here will change anyone's mind, can we keep the subject about something that can be influenced by us?

    How does this related to Spring, a trivial or non-trivial framework, being useful to me? Beyond your opinion that unchecked exceptions are some kind of abomination and that people using them present a truly baffling puzzle to you about how they draw a paycheck :-), what is Spring bringing to the table? Does it have a weakness that can be fixed, beyond exception handling?

    How well does that bean factory work in terms of creating a consistent means of uniting property files and other communal resources? Does it work?

    Does any of Spring work? How well?

    How many people currently support it?

    Is there a roadmap and what is it?

    How can I use Spring and not depend on the Spring API? By introducing another layer? Why do that?

    Slam the thing if you like, but I'm just asking that you do it in terms of Spring. What concrete examples have you personally worked with, using Spring, that caused you a problem because of either its exception handling or other framework components?
  53. Re: Rod's comments[ Go to top ]

    <David>
    How does this related to Spring, a trivial or non-trivial framework, being useful to me? Beyond your opinion that unchecked exceptions are some kind of abomination and that people using them present a truly baffling puzzle to you about how they draw a paycheck :-), what is Spring bringing to the table? Does it have a weakness that can be fixed, beyond exception handling?
    </David>

    David, I think you are being overly defensive here. I don’t understand why you want to draw attention away from one particular flaw in Spring’s design which many find very important. The question still stands: "How do I create robust applications with Spring Framework if at any given point of time I don’t have exact knowledge of which error my code may produce?"

    If you need more arguments on this matter that directly involve Spring API and classes, please browse about in this thread – I personally posted a few.

    Regards,
    Dmitriy Setrakyan
    Fitech Labs, Inc.
    xNova™ - Service Oriented Technology for Java and .NET
  54. Re: Rod's comments[ Go to top ]

    How do I create robust applications with Spring Framework if at any given point of time I don&#8217;t have exact knowledge of which error my code may produce?
    I've already explained that our JDBC exceptions have a single root. So you would know. This root exception, and the whole hierarchy, hasn't changed since the book was published.

    I assume you don't use JDO, either. Or TopLink? Or core Java collections...
  55. Re: Rod's comments[ Go to top ]

    <Rod>
    I've already explained that our JDBC exceptions have a single root. So you would know. This root exception, and the whole hierarchy, hasn't changed since the book was published.
    </Rod>

    Sure... And in my post above (Message #88674) I suggested a better approach to handle good hierarchy of exceptions by having common root (DataAccessException in your case) as a checked exception. Having common root as unchecked runtime exception does not solve the problem – developer still does not know if database related exception is thrown at any particular time in any given method (unless you bring up that Javadoc reasoning again). Or are you implying that any method at any given point of time should be mindful that DataAccessException may pop up all of a sudden?

    <Rod>
    I assume you don't use JDO, either. Or TopLink? Or core Java collections...
    </Rod>

    Well, Rod, as much as I was trying to keep this discussion related to Spring Framework, you are forcing me to digress;-)

    Firstly, JDO and Toplink... In my current line of work (which is producing library-like pre-built services for Java and .NET) we try not to specialize our APIs to any persistence framework since there are so many of them. So, to answer your question, no, I am not currently using JDO or TopLink. However, I know JDO spec almost by heart and I thoroughly evaluated TopLink for a different project. I find both of those persistence spec/frameworks useful for the solution they provide and I am also regretful of the exception handling strategy chosen by both of them.

    Persistence frameworks provide an extremely broad set of features and users often will be willing make a trade-off towards reach functional behavior over a bad exception handling strategy... In short, popularity of JDO and TopLink should be attributed to the reach feature set and not to the exception handling mechanism they have.

    As far as Java collections API, I am a little puzzled why you brought it up. None of the unchecked exceptions it throws will ever happen in production... all those exceptions constitute pure coding bugs and should be junit-ed out before production. However, I can assure you that OptimisticLockingFailureException provided by Spring Framework is recoverable and will often happen in production, and keeping it as unchecked runtime exception is akin planting a trap for developers to fall into.

    Regards,
    Dmitriy Setrakyan
    Fitech Labs, Inc.
    xNova™ - Service Oriented Technology for Java and .NET
  56. Persistence[ Go to top ]

    In short, popularity of JDO and TopLink should be attributed to the rich feature set and not to the exception handling mechanism they have.


    But why are they popular (TopLink after 6 years) if it's impossible to build robust applications with them? You've strongly argued that APIs based on unchecked exceptions are accidents waiting to happen.

    I didn't say they're popular because of their exception handling srategy (although it may have something to do with it). I was pointing out that Spring actually follows the practice of some well-established persistence APIs.
  57. Re: Rod's comments[ Go to top ]

    No offense, but how can I be defensive about something over which I have no stake personally or professionally? If you want to tear into Spring, have at it, but do so in such a way that actually addresses Spring.

    I'm here to read about Spring, not your thoughts of checked vs. unchecked exceptions outside of that context. That is your opinion and I don't share it. The authors don't share it. Again, there are people writing apps deemphasizing checked exceptions, so I just don't think your point here is particularly valid. You say many find it a flaw, and many may, but many also find it a good design decision.

    If you have first-hand knowledge of how this decision caused you a problem, especially using Spring, I'm absolutely interested in hearing about that. It may burn me, and I'll like to know, but my personal experience is that runtime exceptions work well, so let's move on.

    As a side thought, according to the posts here, JDO does the same thing, yet this never seems to come up in any JDO threads.
  58. Questions[ Go to top ]

    David,

    I guess your questions were rhetorical, but I'm going to answer them anyway.

    >How well does that bean factory work in terms of creating a consistent means of uniting property files and other communal resources?
    We've found it to work extremely well. Very consistent: no more digging around to work out the properties file format for a given class. Bean factories are hierarchical, so it's possible to share common definitions.

    >How many people currently support it?
    There are 11 committers. 5 are continually active. Juergen and I are the co-leads of the project.

    >Is there a roadmap and what is it?
    For 1.0 we plan some JDBC enhancements relating to stored procedures returning result sets; we want to implement the latest AOP Alliance APIs; we want to provide web services support; and we want to improve our AOP pointcut support and support for source level metadata. We also want to raise our test coverage from the present 72% towards 80%. (As we're doing mostly test-first development these days, coverage is improving naturally as well.) We also need good AOP samples, in particular.

    Beyond 1.0 we plan to reintroduce the JMS package published with the book and consider dynamic reconfiguration of bean factories. However, we're also keen to have users drive requirements. I think Gavin's done a great job of that with Hibernate, which is one reason it's so successful.

    >How can I use Spring and not depend on the Spring API?
    Via Inversion of Control (IoC). Rather than your application objects invoke Spring to look other objects up, Spring can hook them up via JavaBean properties. Spring can also set DataSource and other properties on your code, when these are exposed as bean properties. Not only does this mean that most app code won't depend on Spring APIs, it means that application code is a delight to test. If you want to practise test first development, you'll find Spring a pleasure to work with.

    Btw, Spring is simple to use but not "miniscule". It covers a lot of ground, so we're pushing 40,000 lines of code.

    Regards,
    Rod
  59. Inversion of Control + Testing[ Go to top ]

    <David>
    How can I use Spring and not depend on the Spring API?
    </David>
    <Rod>
    Via Inversion of Control (IoC). Rather than your application objects invoke Spring to look other objects up, Spring can hook them up via JavaBean properties. Spring can also set DataSource and other properties on your code, when these are exposed as bean properties. Not only does this mean that most app code won't depend on Spring APIs, it means that application code is a delight to test. If you want to practise test first development, you'll find Spring a pleasure to work with.
    <Rod>

    If you follow interface-based design and combine that with IOC the results are truly impressive. In our current system, we have something fairly normal where manufacturers add/edit/delete products. The validation and dao objects are added dynamically by Spring.

    The fun part is when we were asked to provide a batch update process so that the manufacturers can upload product files (.csv) directly into the system. To support this, I simply coded a "CsvDaoImpl" which implemented the "ProductDao" (we were using a "JdbcDaoImpl" for the webapp). By simply adding that new class and an upload page, we configured Spring to reassemble the already created objects, and everything worked.

    Testing was a breeze too since the objects didn't have any reliance on JNDI, initialization, or configuration. All that stuff happened automatically without the objects knowledge, so our test code could be focused (and concise) around testing the objects functionality.

    Trevor
  60. Re: Rod's comments[ Go to top ]

    Nikita,

    we all understand now that you don't like the way Spring handles exceptions (this is not a VB site). So what ? Just don't use it !
    No reason to discriminate an oustanding peace of work given for free over and over again. A much better way would be to build your own framework and let the community decide which one is better.

    The refreshing thing about Rod's book is that it presents solutions coming from practical experience, it's not just another book about a specific technology (EJB, etc). Are you able to write such a book (IMO few are) ?

    Of course I don't agree with some parts of the book, but i still think is a jewel.
  61. Re: Rod's comments[ Go to top ]

    Nikita,

    > If user does not handle database errors (at least generically), the code simply won’t compile – a powerful paradigm lack of which significantly cripples robustness of Spring Framework and all applications using it.

    "Significantly cripples robustness"?? So not only all C# code but also all TopLink and JDO application code is a priori significantly crippled in terms of robustness? No, that's a distortion of the facts - it's as always the responsibility of the developer to care for proper exception handling. The main difference is that checked exceptions _force_ you to care about thrown exceptions while unchecked ones _allow_ you to care about them.

    BTW, doesn't Fitech Labs produce its own middleware product? That's fine of course, but can't you accept that other people make different but nevertheless valid architectural decisions for their middleware products? BTW, what about your .NET support? Significantly crippled in the first place, as .NET doesn't have checked exceptions?? (no insult intended)

    > Many readers suggested that the main reason to use unchecked exception is to simplify the code and get rid of those pesky and annoying try-catch blocks. Sure, using runtime exception can reduce number characters one has to type on the keyboard to produce compilable piece of code. However, if you think that software engineering is all about reducing the number of lines you type – you’re thoroughly misled and you should probably consider the change of your occupation.

    I don't like that tone - you are not talking to some dev kiddies here. Do you want to imply that people like Rod and me don't know what we're talking about? This is just about saving _unnecessary_ try-catch blocks for _unrecoverable_ checked exceptions, not about getting rid of them in general. Of course, try-catch blocks make sense if you can actually deal with a certain exception. This is about cluttered and complex code, not at all about saving some typing. Don't get ridiculous - please.
     
    > Another interesting myth is that unchecked exception allow user to catch exceptions selectively (thus potentially simplifying the error handling code), i.e. only those the user knows will be thrown and he/she can handle, and to ignore rest of them using some sort of global catch for such ignored exceptions. Well, such “selectivity” among many other things basically means that user must be fully aware of the underline code implementation thus incurring extreme coupling.

    No more coupling than with checked exceptions, as the unchecked exceptions are part of the API too. Let's not forget that unchecked exceptions can be declared in "throws" clauses too.

    So each layer should care about handling all exceptions of the next one below, be it checked or unchecked - if it can deal with them of course. Else, it should rethrow checked ones as exceptions of its own API, it can declare unchecked ones in its own "throws" clauses too if that makes sense, and it can also simply let unrecoverable ones through without declaration. IMO, application code should just have to care about the API layer that it uses directly, everything below is the responsibility of that layer.

    Unrecoverable errors are a different thing, they can and should normally get through to the top - except if some intermediate code untypically decides to handle some of them. What about OutOfMemoryError or NoClassDefFoundError? Should that be checked exceptions according to your reasoning?

    > Funny enough, this argument goes along with the argument of making all private variables public to allow users “optimize” or “simplify” their use of such class – indeed, code will still compile, it will be probably shorter, no more of those pesky public getters/setters; I’ve met people who seriously argued that this technique is great b/c it gives a significant performance boost :-) …

    Now you're _really_ getting ridiculous. Who's ever said such a thing on that thread, or any other Spring Framework resource? Mentioning the use of unchecked exceptions and such "optimization" crap in one posting can indeed be considered an insult, IMHO.

    > But probably most simple to understand and yet very powerful argument in favor of intelligent usage of checked exceptions is: there is no way to know what unchecked exception to catch or expect in any given point of program unless you either 100% rely on documentation or traverse the entire call graph in source code.

    And there is no way to know what checked exceptions got swallowed and rethrown as another checked exception at any given point of program either. What does "throws MyApplicationException" really mean, or "throws SQLException" for that matter? You can't find out what actual exception subclasses - that you could potentially handle - can get thrown by looking at the API. So you have to resort to catch-and-rethrow, or worse things like swallowing.

    So should a high API layer of the application have to carry a lot of distinct checked exceptions with it, for all potential faults in lower layers? Not really. One general meaningless application exception type, without known subclasses, carrying some rethrown ones? Not really either. All the specific lower-level ones, from SQLException upwards? That would completely break any abstraction.

    Finally, one thing is a fact: People are deliberately building robust systems without heavy use of checked exceptions, both in Java and in other programming languages. They obviously cannot all be morons, so the world cannot be as black and white as you intend to paint it - the issue isn't that simple.

    Juergen
  62. Re: Rod's comments[ Go to top ]

    Hi Juergen,
    Thanks for the thoughtful reply.

    Yes, at Fitech we develop cross-paradigm middleware for Java and .NET that consists of a large set of pre-build services. Specifically for .NET, we ship AOP-based tool that introduces checked exception into any CLR-based language (VB.NET, C# and Managed C++). So, we have taken robustness extremely seriously.

    As far as JDO (repeating it again), you should separate “technical marketing” from technical reasoning. Checked exception simply won’t work in JDO by definition and JDO designers had no other choice.

    As far as you and Rod (and reducing number of lines), I specifically said “many readers”. You guys didn’t imply that stupid argumentation – many, many others did in this and other threads and forums. But I agree that this topic can be slippery slope.

    And finally, as you can see I don’t use my experience or “many systems that I’ve successfully built” in my argumentation. I firmly believe that sheer number of years, number of books (nothing to do with Rod), articles or systems written and built has very little do with actual intellectual abilities and validness of views of any given individual. And therefore I don’t buy your argument that “...people are deliberately building robust systems without heavy use of checked exceptions...”. I could then argue that people deliberately build complex server-side applications in PERL and start advocating this as a valid venue.

    Regards,
    Nikita Ivanov.
  63. Re: Rod's comments[ Go to top ]

    \Juergen Hoeller\
    I don't like that tone - you are not talking to some dev kiddies here. Do you want to imply that people like Rod and me don't know what we're talking about? This is just about saving _unnecessary_ try-catch blocks for _unrecoverable_ checked exceptions, not about getting rid of them in general. Of course, try-catch blocks make sense if you can actually deal with a certain exception. This is about cluttered and complex code, not at all about saving some typing. Don't get ridiculous - please.
    \Juergen Hoeller\

    I don't think you're stating the actual concerns here very well. It's not about unrecoverable checked exceptions - if it was, something like Spring would have recoverable exceptions checked. Also, I'd be inclined to say that Rod is dodging and weaving more than answering the direct questions.

    \Juergen Hoeller\
    And there is no way to know what checked exceptions got swallowed and rethrown as another checked exception at any given point of program either. What does "throws MyApplicationException" really mean, or "throws SQLException" for that matter? You can't find out what actual exception subclasses - that you could potentially handle - can get thrown by looking at the API. So you have to resort to catch-and-rethrow, or worse things like swallowing.
    \Juergen Hoeller\

    Let's look at the reality of projects. Most everyone uses a layered approach to software, with many of their own layers, and APIs/frameworks to do much of their grunt work. I agree you can't really know what's going on in the frameworks/APIs, but you can obviously know what's going on in your own code.

    Within your own layers, you can _easily_ determine what checked exceptions are swallowed, how they are handled, and what ones are passed on. This can be done programatically. You can analyze the code a number of ways to see how well it handles checked exceptions. You can pinpoint trouble spots, and design flaws (some of which you pointed out) can be spotted and fixed.

    _You cannot do this with unchecked exceptions_. You can spot places where someone already has a try...catch block, but you cannot find unchecked exceptions that aren't handled. Period, full stop.

    That is the difference between the two approaches - on one hand, easily identifying what's there, and on the other hand, trying to identify something whose existence you can't even discover.

    When it comes down to it, every argument I've seen against checked exceptions has always come down to "I don't like extra error handling code cluttering my main line code". Every other argument is smoke and mirrors for this one. And people see bad checked exception hierarchies and knee-jerk just as radically in the opposite direction. Because some APIs foster ugly exception handling, they turn around 180 degrees and abandon verifiability altogether. It's the same phenomena you see with something like EJBs - they're misunderstood at first, then loved for awhile, then people find problems with one or more aspects of it, and then they knee-jerk around and reject the entire concept and go to something completely different (more out of spite than anything else).

    Spring could _easily_ have had a very sane and very usable exception model with a combination of checked and unchecked exceptions, and shown that you can be moderate in your approach and succeed. Instead, Spring shows the author's obvious (and somewhat deserved, admittedly) disgust with some aspects of EJBs, and therefore abandoned checked exceptions completely. In doing so he avoided the obvious issues with EJB exceptions - but now has substituted a brand new problem in its place.

    As for other persistence engines - most of them are dynamic enough by nature that checked exceptions likely would have been impossible. There, there's a solid technical reason for it. Here, there isn't any good reason, just the author's bad taste in his mouth from EJBs.

        -Mike
  64. Re: Rod's comments[ Go to top ]

    I don't think you're stating the actual concerns here very well. It's not about unrecoverable checked exceptions - if it was, something like Spring would have recoverable exceptions checked. Also, I'd be inclined to say that Rod is dodging and weaving more than answering the direct questions.


    For a quite a while, this thread hasn't been about Spring itself anymore, so I targetted at Nikita's blunt "all they want to do is save some typing" comment. In general, actual developer complaints and the solutions for them are about unrecoverable checked exceptions, and I consider this a very valid case.

    But nice to go back to Spring a bit... Spring aims to adopt consistent exception hierarchies, mainly unchecked ones. Given Java's "RuntimeException extends Exception", it's impossible to have a common root for a mixed exception hierarchy. So partly for the sake of consistency, some data access exceptions that are _potentially_ recoverable are unchecked, right.

    In many cases, all data access exceptions are unrecoverable anyway. You're so focussed on that freaking OptimisticLockingFailureException that you distract from the fact that _most_ data access exceptions are unrecoverable by any means. Of course, there is a tradeoff involved: I believe that the tradeoff is worth it - you don't, fine, then don't use Spring's data access framework.

    And again, optimistic locking failures only occur when leveraging optimistic transaction checks. So why have to deal with it in all application code when there often aren't any optimistic transactions involved? Would you suggest to throw it as checked exception on _each and every_ data access method, no matter if transactional at all? There is no chance to apply such declarations selectively with a general data access framework.

    > _You cannot do this with unchecked exceptions_. You can spot places where someone already has a try...catch block, but you cannot find unchecked exceptions that aren't handled. Period, full stop.
    >
    > That is the difference between the two approaches - on one hand, easily identifying what's there, and on the other hand, trying to identify something whose existence you can't even discover.

    But you can find declared unchecked exceptions (like "throws DataAccessException"), with some effort even specifically ones that aren't handled by try-catch blocks.

    You're mainly talking about _undeclared_ unchecked exceptions. This is somewhat similar to generic checked exceptions: You can't know what's underneath, at least not which specific exception subclasses. In the one case, you just know "RuntimeException", in the other case just "SQLException". The latter isn't much better, as you cannot recover from an SQLException in a generic way -so catch and rethrow.

    I prefer declared unchecked exceptions for a _data access layer_. What does a checked "throws DataAccessException" really buy you? That you have to catch and rethrow it in your business objects in any case? The point is: For specific data access exception handling with almost every persistence tool, you have to look into the documentation anyway, to be able to catch _specific exception subclasses_. Or worse, specific SQL error codes in SQLExceptions.

    > Spring could _easily_ have had a very sane and very usable exception model with a combination of checked and unchecked exceptions, and shown that you can be moderate in your approach and succeed.

    Spring _does have_ a sane and usable exception model, just like TopLink and JDO, no matter how much you try to discredit the approach. There are tradeoffs involved, noone tries to dispute that, but it definitely isn't insane or unusable. And I've already elaborated on consistency with mixed checked/unchecked exception hierachies.

    > As for other persistence engines - most of them are dynamic enough by nature that checked exceptions likely would have been impossible. There, there's a solid technical reason for it. Here, there isn't any good reason, just the author's bad taste in his mouth from EJBs.

    Again, and Gavin's comment shows that too: Persistence engines can choose to use unchecked data access exceptions no matter if checked exceptions were possible. I believe that the respective designers of TopLink and JDO were not just reacting to some lack of choice. They could have tried to use checked exceptions on all their API methods, and just throw unchecked ones from lazy-loading proxies and the like. But they didn't, they deliberately chose a consistent declared unchecked exception approach.

    Finally, I won't comment on your blunt "author's taste" statements - they speak for themselves. If the thread continues that way, I'm out, at least with respect to the exception debate.

    Juergen
  65. Re: Rod's comments[ Go to top ]

    Juergen, well said ;-)
  66. Exception hierarchies[ Go to top ]

    Hi Juergen,

    > Granted, properly using checked exception and *understand* them from system design and architecture standpoints requires more than just average IQ but it&#8217;s certainly not a rocket science. Professional incompetence and just simple laziness are lame excuses for poor engineering practice.

    You can't seriously mean that this is about IQ
    , or the unability to grasp the concept. Any mechanism can get subverted in many ways, so can both the use of checked and unchecked exceptions. I agree though that it requires some understanding and a lot of practice to get a feeling for when to apply either type of exception, especially when designing a framework or API.

    In the past, I've seen too many projects with "catch(Exception)" or "throws Exception" clauses throughout the code. I guess there are really more problems created by overuse (and inappropriate handling) of checked exceptions than by unchecked exceptions.
     
    > Some of the people of the Eckel&#8217;s discussion hacked the javac to stop checking for checked exception so their lives would be easier... It is startling that people can be so brainwashed on the technical subject and completly loose the grip on reality of their work.

    Well, we don't need to discuss this. Hacking javac isn't a solution by any means. But designing meaningful unchecked exception hierarchies for certain APIs is perfectly viable, IMHO. What is indeed startling is that a subject like this can be such a religious issue...

    Juergen
  67. Back to the subject[ Go to top ]

    I'd prefer to go back to Spring _itself_ now. There's such a lot of useful stuff in the framework that I really don't see why we should continue debating just one single aspect of it!

    Any comments e.g. on the Hibernate support, the Spring Beans vs PicoContainer article, Spring Web MVC vs Struts/WebWork on top of a Spring middle tier, etc? Diving into this is easy: The articles in the documentation section of the website are a good start, and the Javadoc is extensive.

    Juergen
  68. Back to the subject[ Go to top ]

    Any comments e.g. on the Hibernate support, the Spring Beans vs PicoContainer article, Spring Web MVC vs Struts/WebWork on top of a Spring middle tier, etc? Diving into this is easy: The articles in the documentation section of the website are a good start, and the Javadoc is extensive.


    Please also let us know also if there are areas where it's hard to get to grips with Spring--we are working hard to improve our documentation and examples, so please let us know where we can do better.
  69. Back to the subject[ Go to top ]

    I'm glad there's documentation stuff provided with such an early release. IMO the tutorial should be completely rewritten or at least be renamed with one of the next releases. A good tutorial should start with installation stuff (required libraries, etc). The current version seems like a loose collection of samples and it's out of date.
    It's not a big problem after reading the (excellent) book, I don't know about people who didn't read it.
    But I don't want to criticize that much because there IS documentation. WebWork still doesn't have a tutorial (except the one where the link is broken).

    The countries sample is funny when choosing German as language (is this a google translation ?) :-)

    Keep on the good work !
  70. Back to the subject[ Go to top ]

    I'm glad there's documentation stuff provided with such an early release. IMO the tutorial should be completely rewritten or at least be renamed with one of the next releases. A good tutorial should start with installation stuff (required libraries, etc). The current version seems like a loose collection of samples and it's out of date.

    > It's not a big problem after reading the (excellent) book, I don't know about people who didn't read it.
    > But I don't want to criticize that much because there IS documentation. WebWork still doesn't have a tutorial (except the one where the link is broken).
    >
    > The countries sample is funny when choosing German as language (is this a google translation ?) :-)
    >
    > Keep on the good work !
  71. Back to the subject[ Go to top ]

    Lars,

    > I'm glad there's documentation stuff provided with such an early release. IMO the tutorial should be completely rewritten or at least be renamed with one of the next releases. A good tutorial should start with installation stuff (required libraries, etc). The current version seems like a loose collection of samples and it's out of date.

    I have been keeping notes as I developed a basic MVC application from scratch. I have put these notes into a HTML document that is now available on the
    Demo/Tutorial Page on the Spring website (It's under 'Other Documents' at the bottom of the page). This is still a work in progress and not complete, but what is available now covers the basic steps that you need to go through to set up a very basic web application using Spring.

    Regards,

    Thomas
  72. Back to the subject[ Go to top ]

    I have been keeping notes as I developed a basic MVC application from scratch. I have put these notes into a HTML document that is now available on the

    > Demo/Tutorial Page on the Spring website (It's under 'Other Documents' at the bottom of the page). This is still a work in progress and not complete, but what is available now covers the basic steps that you need to go through to set up a very basic web application using Spring.

    Thomas,

    I think good documentation is one of the key factors for success and wide acceptance of any kind of software (look at Hibernate). I'm using WebWork for one of my projects and it's working very well. If there's a problem with the framework or something I don't understand I look into the source - no problem.

    The problem is that not all of my co-workers are able to do this and I've got some extra work explaining WebWork.
    Another reason providing good documentation is that time is limited and missing documentation may prevent people from trying out new software.

    As I said before: Keep on the good work !
  73. Exception hierarchies[ Go to top ]

    I find it amusing to hear the large number of people who have claimed that using unchecked exceptions exclusively, especially in APIs, has lead to an increase in code quality. To paraphrase this thread and many others....these super beings always have global handlers (which can apparently intelligently handle anything). They always read the documentation in detail and thoughtfully consider each exception. The documentation always documents each exception that can be thrown. They have no problem tracking down all unchecked exceptions from multiple APIs they happen to be using from a single class. Their unit tests and other tests always test all exceptional conditions, even hard failures. They always, consistently go through all this effort, and their code quality increases - and they proudly state how much time they saved doing all of the above stuff as compared to a compiler pointing out uncaught checked exceptions and dealing with them then. And they never seem to have to sort out production problems from uncaught RuntimeExceptions.

    God, I wish I was one of those people, or that I even worked with them.

        -Mike
  74. Exception hierarchies[ Go to top ]

    *sigh* Again on exceptions...

    > ..who have claimed that using unchecked exceptions exclusively, especially in APIs...

    Exclusively for exceptions at _certain_ API levels, definitely not for all APIs, especially lower-level ones. We're talking about layers here that shouldn't have to care about resource handling. Lower-level layers have to - checked exceptions make sense here in many respects.

    > To paraphrase this thread and many others....these super beings always have global handlers (which can apparently intelligently handle anything).

    A "global handler" can only exist at the uppermost layer of the application, like the servlet request processor in the case of a web app. It will handle all unrecoverable faults resp. everything that the application didn't decide to handle itself. Such a global handler can of course only be plain dumb, as it will just log the exception in some generic way.

    > They always read the documentation in detail and thoughtfully consider each exception. The documentation always documents each exception that can be thrown. They have no problem tracking down all unchecked exceptions from multiple APIs they happen to be using from a single class. Their unit tests and other tests always test all exceptional conditions, even hard failures.

    Of course this isn't that easy. But it doesn't get easier with myriads of checked exceptions that are hard to recover from, whose catch clauses clutter up all sorts of code. And I have seen much manual JDBC access code that didn't get the resource cleanup right in some way, due to all those methods throwing generic SQLException.

    The problem is that even with checked exceptions, many people just care about the common root class like SQLException. Often such exceptions just get rethrown or wrapped, without checking for particular exception subclasses that might be recoverable. Such applications typically end up with very simplistic exception handling, despite checked exceptions. So often generic checked exceptions aren't any better than having to care for a well-defined unchecked exception hierarchy.

    You must really love JTA then: The 4 unrelated checked exceptions that UserTransaction.commit throws should match your taste. Seriously, for many developers this results in a dumb try block with 4 catch clauses, all simply logging the respective exception, or rethrowing a generic one. IMO, JTA is a good example for silly use of checked exceptions: The designers should at least have introduced a common base class for those exceptions.

    BTW, Spring's abstract transaction handling makes leveraging JTA as easy as any other transaction strategy like native JDBC or native Hibernate, with the choice between programmatic or declarative demarcation for all of them :-)

    Juergen
  75. Exception hierarchies[ Go to top ]

    \Juergen Hoeller\
    Of course this isn't that easy. But it doesn't get easier with myriads of checked exceptions that are hard to recover from, whose catch clauses clutter up all sorts of code. And I have seen much manual JDBC access code that didn't get the resource cleanup right in some way, due to all those methods throwing generic SQLException.
    \Juergen Hoeller\

    I think you're missing the fundamental point: I can progamatically check that all checked exceptions are handled in some manner at least. Even if they're badly handled, I can also very easily check _that_ with a simple tool.

    With unchecked exceptions, there is no way programatically to know what exceptions are being missed. Period. The developer must do the full work of the compiler and root about on their own to try to find what exceptions are thrown, and it may not be physically possible for them to _ever_ know what exceptions might come out.

    Bad developers, as many people have said, are bad developers. The problem is that a really, really good developer can try their damnedest and still miss things when unchecked exceptions are used - things that they may actively want to deal with.

    In the type of software I work with, occasional extra lines of error code (exception related or otherwise), even if not strictly required, is the cost of doing business, and no big deal. We value convenience, but we don't squawk at having to write a few extra lines of code here and there. Unchecked exceptions, on the other hand, are our nightmare - when one of those gets thrown in production, doesn't get caught (or only caught by a useless global handler which can't do anything intelligent), and it's plain that the developer did their best to have really good error handling, then it's a sad day for everyone concerned. We'd rather type some extra lines occasionally, and have the compiler double-check our work, then have an exception pop out of the blue that we could never have known about or looked for. And the compiler is a good low-level nanny for newcomers to the language or development in general.

        -Mike
  76. RE: Exception hierarchies[ Go to top ]

    <Mike>
    I think you're missing the fundamental point: I can progamatically check that all checked exceptions are handled in some manner at least. Even if they're badly handled, I can also very easily check _that_ with a simple tool.
    </Mike>

    Why can't you have a tool to check that all unchecked exceptions are documented? Eg.

    public void someMethod(){
      someStuff(); // throws unchecked exception
    }

    The tool could check what exceptions are thrown by someStuff and make sure that someMethod declares that these exceptions are thrown. Anyway I'm not sure if this would work, but it seems like it would.

    <Mike>
    With unchecked exceptions, there is no way programatically to know what exceptions are being missed. Period. The developer must do the full work of the compiler and root about on their own to try to find what exceptions are thrown, and it may not be physically possible for them to _ever_ know what exceptions might come out.
    </Mike>

    (Unit and Functional) Testing should detect unhandled exceptions. Yes having compiler checking is better then runtime checking. But for fatal exceptions that you want to pass up to the presentation layer, it is beter to use unchecked exceptions IMHO. Using checked exceptions for fatal errors can result in lose in stack trace and the wrapping of the exception increases LOC for no good reason (since we aren't adding any extra information).

    Yeah having extra lines of code is not a problem. But when you have extra lines that add no value then it is a problem. As for lack of documentation of unchecked exceptions. Well I don't see why we can't have a tool that checks this.
  77. Exception hierarchies[ Go to top ]

    Bad developers, as many people have said, are bad developers. The problem is that a really, really good developer can try their damnedest and still miss things when unchecked exceptions are used - things that they may actively want to deal with.

    >
    I am one of bad and lazy developers and I think it better not dublicate code or introduce useless error wrappers, API adapters and fight with exeptions "manualy". Try some AOP framework, SpringFramework is a good one too, I am sure you will be "bad and lazy" developer too after you will try AOP.
  78. Exception hierarchies[ Go to top ]

    <nikita>
    As far as Bruce Eckel&#8217;s comments, they were ridiculed countless times already so I won&#8217;t repeat it here
    </nikita>
    I think we should move this discussion back to one of the threads devoted to checked vs unchecked exception--if there's anything more for the proponents of each side of the argument to say. Otherwise we'll just end up repeating ourselves in a new thread.

    As for whether Bruce's comments were "ridiculed," I've seen a lot of heated criticisms of his point of view, but haven't been convinced by any of the counter-arguments. I would say "attempted ridicule" was closer to the mark. I'm not sure ridicule is the right note to strike in a technical discussion, either.

    Regards,
    Rod
  79. Exception hierarchies[ Go to top ]

    To bring the discussion back to Spring's take on exception handling, I think having a meaningful hierarchy of exceptions is very important. Discussion around checked/unchecked is only part of the picture. Spring does not throw unchecked exceptions like confetti. There is a consistent hierarchy, so if you want to catch DataAccessException (with JDBC, JDO integration etc) you can do so and be sure you've caught any exceptions Spring will throw for data access operations. But equally, you can choose to go in only at the point of the hierarchy you're interested in, and think you can recover from.

    I think a good API should always provide a consistent exception hierarchy. If an API using unchecked exceptions throws a bewildering variety of exceptions with no common root, this is bad. But that's bad design in itself. If an API using checked exceptions forces code using it to catch multiple exceptions without a common root in order to do anything, it can become almost unusable. (Of course there are some cases where two or more completely different things can go wrong.)

    Regards,
    Rod
  80. Exception hierarchies[ Go to top ]

    <Rod>
    I think a good API should always provide a consistent exception hierarchy. If an API using unchecked exceptions throws a bewildering variety of exceptions with no common root, this is bad. But that's bad design in itself. If an API using checked exceptions forces code using it to catch multiple exceptions without a common root in order to do anything, it can become almost unusable.
    </Rod>
     
    An extremely useful point. However, consistent exception hierarchy should rather pertain to checked exceptions. Having checked exceptions with common root is a viable design technique and has been around for ages. Using Spring Framework as an example at hand, I believe the framework would become much more solid and robust if, for instance, DataAccessException (the common root) would become a checked exception. Without forcing user to catch all exceptions for DAO access, this technique would non-intrusively introduce a notion of database-error-awareness into user’s code. If user does not handle database errors (at least generically), the code simply won’t compile – a powerful paradigm lack of which significantly cripples robustness of Spring Framework and all applications using it.

    Hope this helps,
    Dmitriy Setrakyan
    Fitech Labs, Inc.
    xNova™ - Service Oriented Technology for Java and .NET
  81. Exception hierarchies[ Go to top ]

    <Dmitriy>
    Using Spring Framework as an example at hand, I believe the framework would become much more solid and robust if, for instance, DataAccessException (the common root) would become a checked exception. Without forcing user to catch all exceptions for DAO access, this technique would non-intrusively introduce a notion of database-error-awareness into user’s code. If user does not handle database errors (at least generically), the code simply won’t compile
    </Dmitriy>

    How do checked exception provide more solid or robut when bad programmers can just swallow the exception without handling it? If I can not handle a checked exception and need to display an error message to the user then having to catch the exception in the business layer does not add any value, increase LOC, and can cause (full or partial) lose of the stack trace. Checked exceptions don't solve the problems that they set out to. Having said that they are still useful when they must be handled by the calling code (eg. they indicate an error result). I recommend you read the Chapter 4 from Rod's book to see what I'm talking about.
  82. Checked vs Unchecked exceptions[ Go to top ]

    IMHO checked exceptions don't help to ensure correct code. In fact I would say checked exceptions can make matters worse. If you are consume the exception:
    try{
      doStuff();
    }catch(SomeCheckedException e){}

    Then you are not getting a stack trace, yet something could be going wrong. Yeah some exceptions should be handled, but checked exceptions doesn't ensure it and you can't always add throws clause to the method (like when you are implementing an interface or overriding a method).

    On another note, I like that Spring translates SQLException into more meanful exceptions. I'll take a closer look when I get time.
  83. IMHO checked exceptions don't help to ensure correct code. In fact I would say checked exceptions can make matters worse. If you are consume the exception:

    > try{
    >   doStuff();
    > }catch(SomeCheckedException e){}

    I agree with this, checked exceptions are very dangerous. We can rewrite this example this way:
    2. void interfaceMethod(){
     try{
       doStuff();
     }catch(SomeCheckedException e){
       Log.error(e);
     }
    }
    This is better, but it is a code doublication.

    3. void interfaceMethod()throws MyCheckedExeption{
     try{
       doStuff();
     }catch(SomeCheckedException e){
        throw new MyCheckedExeption(e);
     }
    }
    This is much better, but it does nothing more than unchecked exeptions do.
    Well designed applications have global exeption handler and there is no "unhandled exception", checked exeption adds garbage to code, but solves nothing or "make matters worse".

    BTW. I was a very big "checked exeption fan" too.
  84. Fainthearted...[ Go to top ]

    <thomas>
    I would defenitely encourage anybody to catch this exception and handle it - but only if they expect their use of the framework to potentially throw this kind of error. I wouldn't want to force everybody using the framework to use a try-catch block for some exception that would never be thrown in their environment.

    We had to pick one way of handling all different types of excpetions thrown during data access, and to be consistent we decided to handle all of them the same way. Singling out a subset and forcing the developers to catch them would kind of defeat our original approach.
    </thomas>

    It is a sad story... Not that I believe or hope that people as such can be convinced or taught otherwise but it’s appalling that such fainthearted “designs” are prescribed and accepted so easily. Of course, it’s my personal opinion but I think it regrettably reflects the overall state of design & architectural skills en-mass in my view...

    Peace,
    Nikita Ivanov.
    Fitech Labs.
  85. Fainthearted...[ Go to top ]

    Nikita
     
    > It is a sad story... Not that I believe or hope that people as such can be convinced or taught otherwise but it’s appalling that such fainthearted “designs” are prescribed and accepted so easily. Of course, it’s my personal opinion but I think it regrettably reflects the overall state of design & architectural skills en-mass in my view...
    >

    Aren't you taking the absence or presence of one language feature a bit too far? I beleive that the majority of programming languages do not support checked exceptions - do you consider the use of any of them "fainthearted"?

    Regards,

    Thomas
  86. Fainthearted...[ Go to top ]

    \Thomas Risberg\
    Aren't you taking the absence or presence of one language feature a bit too far? I beleive that the majority of programming languages do not support checked exceptions - do you consider the use of any of them "fainthearted"?
    \Thomas Risberg\

    Statistics of this nature doesn't work too well in technical discussions.

    There are only three highly popular languages that use exceptions - Java, C#, and C++. C++ _could not_ use checked exceptions, because it would have broken all pre-exception code. Java chose to allow checked and unchecked exceptions. C# chose unchecked exceptions only.

    So we have one language that had no choice, another that chose both, and a third which allows only unchecked.

    Erroneous statements about "majorities" aside (unless C# is a majority, or you're lumping completely dynamically typed languages into the mix), the true question is what works best in a wide variety of situations. I believe, personally, that unchecked exceptions are going to be shown as one of the "XYZ considered dangerous" topics of the future. For all the statements I've heard in its defense, the _reality_ on real projects is that people like it for the laziness factor. They find try...catch blocks annoying, and are relieved that "experts" have eliminated them for them. Except that the underlying errors haven't been eliminated, just the need to deal with them has been.

         -Mike
  87. Fainthearted...[ Go to top ]

    /Mike Spille/
    There are only three highly popular languages that use exceptions - Java, C#, and C++.
    /Mike Spille/

    Borland Object Pascal aka Delphi. All exceptions are unchecked. When I first converted from Delphi to Java, I was stumbled upon checked exceptions. I could not get how is it possible to declare all exceptions method could throw. Until I realized that Java has unchecked exceptions as well ;)

    I think that if a project declares base "application" exception, then there is no big difference of using checked vs. unchecked.
  88. RuntimeExceptions Rock![ Go to top ]

    I have to chime in on the whole checked vs. unchecked exceptions issue. I couldn't be happier that Spring has adopted the unchecked exception route. About 6 months ago we converted all our code to throw only unchecked exceptions. In addition, we convert all checked exceptions to unchecked exceptions as required. I can't say enough how this has simplified our coding and "freed" our developers.

    We no longer have to worry about cactching things we cannot recover from. However, we still catch whatever exceptions we want as needed and when we can deal with them locally. Otherwise, all exceptions bubble up to a global error handler that displays a user friendly error page (no 500 errors!) while logging and emailing the stack trace to us for investigation.

    At least for web applications, unchecked exceptions are the way to go. All the benifits of checked exceptions with none of the hassles. I encourage the Spring developers to stand firm on their forward thinking and stick with unchecked exceptions!

    Keep up the good work.
  89. publisher[ Go to top ]

    then is Wrox also going to publish your next book?
  90. publisher[ Go to top ]

    Probably the Wrox brand as part of Wiley. Wrox will be a viable brand going forward.
  91. Spring[ Go to top ]

    Great work guys!

    I've been looking forward to this announcement since talking to Juergen at TSS.

    And I'm finally completely sold on IoC, after so long of just not "getting it" :)
  92. exceptions[ Go to top ]

    Just a random comment on this interminable exceptions debate:


    * Hibernate uses checked exceptions as much as possible.
    * I consider that decision to be a mistake (though we don't plan to change it).


    ;)
  93. exceptions[ Go to top ]

    <gavin>
    * Hibernate uses checked exceptions as much as possible.
    * I consider that decision to be a mistake (though we don't plan to change it).
    </gavin>
    Thanks for your honesty, Gavin. Of course you now have a good API and a lot of users, and changing is not really an option. (You don't want to have a thread like this on Hibernate, anyway :-)

    Btw, my opinions on exception handling have nothing to do with my views on EJB. Local EJBs don't necessarily involve many checked exceptions anyway.

    Regards,
    Rod
  94. :)[ Go to top ]

    Thanks for your honesty, Gavin. Of course you now have a good API and a lot of users, and changing is not really an option. (You don't want to have a thread like this on Hibernate, anyway :-) <

    Of course, if users want to use the Spring Framework, they can circumvent this design flaw ;)


    Another option for our users is to wrap Hibernate in an API that uses unchecked exceptions (assuming they prefer this, as I do).
  95. Hibernate exceptions[ Go to top ]

    Another option for our users is to wrap Hibernate in an API that uses unchecked exceptions (assuming they prefer this, as I do).


    Indeed. That is exactly what we do, and it makes sense for us. In my experience, almost any HibernateException that gets thrown was a result of:

    - Incorrect Hiberante mapping file (config error)
    - Bad table/column name (config error)
    - Incorrect use of Hibernate APIs (programmitic error - usually it is me not using collections the way Hibernate wants me to)

    All of these are not run time errors - they are errors that should be *fixed* by the time the build goes to production. So, I don't want to complicate my code by catching exceptions that a) in all likelyhood will *not* happen in production and b) I want to progagate up the chain wrapped in a RuntimeException (our SystemException) that is handled uniformly.

    Besides, if all of my XxxDaoHibernate objects caught these exceptions, what would they do? The transaction has been rolled back - our Hibernate Facade does this automagically). The error will be logged - all SystemExceptions are logged, displaying all nested exception's stack traces as well. I don't know the *specific reason* for the error, so all I can do is report a generic error to the end user - I do that *anyway* with any SystemException. I don't see what catching the checked HibernateException buys me.

    To this day, I can't recall this ever being an issue in production.

    Ryan
  96. Hibernate exceptions[ Go to top ]

    Hi Ryan,

    That's exactly the motivation behing Spring's Hibernate support, enriched with IoC-style templating for simplified DAO implementations, and a Hibernate implementation of Spring's abstract transaction management. Spring provides all of the benefits that you've mentioned, including automatic rollback and uniform logging.

    Allowing for easy integration of data access tools into the overall application architecture, and for easy adaptation to a variety of environments (in terms of transaction strategy, mixing data access tools, etc): That's what Spring's data access and transaction support is about, be it with Hibernate, JDO, or plain JDBC.

    Again, I'd like to encourage everyone to have a look at Spring's data access support, with Hibernate as a "first class tool". The respective article in the documentation section of the Spring website and in the community area of the Hibernate website is a good start.

    Finally, look out for our upcoming release 0.9.1, featuring even more Hibernate integration conveniences (among other enhancements like CGLIB support etc)!

    Juergen
  97. Wish I'd thought of Spring[ Go to top ]

    I've been using the Spring framework since it's inception and am extremely pleased with it so far. It is already the basis for my companies most recent project, and has been in production for over a month without problems (at least not Spring-related :) ). We are also going to be starting 1 new desktop application and 2 new webapps over the summer that will all be based on Spring.

    To me the best thing about Spring is the fact that it is totally non-intrusive on your code. I've been able to create a sound business-based design and simply "strap-on" the framework. I'd also strongly recommend Rod's book which details the basis for Spring and challenges a lot of the conventional "wisdom" in favor of practical, real-world solutions (which is what I need to stay employed).

    Trevor D. Cook
  98. I think 2 things are clear.

    First, regardless of which side you agree with, both are very passionate and have taken the time to evaluate their reasons (which makes the debate interesting).

    Second, Spring uses unchecked exceptions, right or wrong. If you disagree with this usage then maybe Spring isn't for you. Also realize that due to the "consistent exception hierarchy" Rod refers to and the availability of source code, you are free to change the exceptions back to being checked (although I would STRONGLY discourage this).

    In deference to the myriad of other features Spring has to offer, I think this focus on checked/unchecked is clouding discussion around Spring. While this debate is a good one, Dmitriy started a great thread on this issue a couple months ago. I would encourage anyone interested in this debate and the merits of both camps to check it out at http://www.theserverside.com/home/thread.jsp?thread_id=19192 and if they have more to add, simply start posting and give the thread life again. This will make it easier for those following Spring to have a focused discussion, and those interested in the checked/unchecked debate not to be bothered by off-topic stuff like how Spring simplifies J2EE and how to code "with" a framework rather than "to it".
  99. <quote>Spring uses unchecked exceptions, right or wrong</quote>
    Discussion has primarily focused on Spring JDBC. Like Spring's transaction management abstraction, this uses unchecked exceptions, and the experience of Spring users tends to indicate that this was a good decision. (It's also consistent with other persistence APIs such as TopLink and JDO: Spring was not the first framework to take this approach to persistence.)

    However, Spring offers much more than its JDBC abstraction. For example, its powerful JavaBeans-based configuration management and MVC web framework don't impose any preference for unchecked exceptions on your code, in the same way that Spring doesn't impose its APIs on your code. So if you prefer to use checked exceptions exclusively in your business logic, Spring won't stop you.

    Spring has chosen unchecked exceptions for its low-level APIs. This doesn't mean that we believe there's no place for checked exceptions in your code. Even with Spring JDBC, you could standardize on your own checked exceptions in your DAOs and catch (DataAccessException and interesting subclasses) and wrap them after Spring JDBC operations.

    Regards,
    Rod
  100. Rod,

    I have perspective on the question I haven't seen articulated here, a refactoring if you will. I also have a question for you if I may. It seems to me that we can reduce a lot of the actual technical disagreement to the fact that checked exceptions seem to have more than one intent:

    1. Force the client code to catch every exception type in the signature as an attempt to enforce good coding practice. The logic against this is hard to refute. As you and others have said, it's easily circumvented and is not even the best practice in many cases. How to _handle_ an exception seems more like a design decision than an axiomatic language feature. If not quite locking you into one approach, it at least makes it inconvenient and tends to clutter the code unnecessarily when you choose another.

    2. Publication of an exception signature. I think we can all agree that this is always a good practice. It allows the developer to be sure that they have considered everything that _might_ go wrong, without forcing a handling strategy on them. The trick would be to provide a way to detect the transitive closure of throwable exceptions from a given method without forcing the method writer to do it manually (IOW, method exception signature only needs those thrown in the method). The ideal would be to provide this as part of the language without point 1 above. In lieu of that, some have pointed out that this could be done with a tool (somebody just has to write it). Or perhaps it could be a compiler feature; maybe already is on some?

    I would submit that the "failed experiment" part of checked exceptions lies in point 1. Please post any comment you care to on this. Thx. Everyone else, if you don't find this at least remotely plausible, please leave me in my ignorance. ;-) Thx.

    My question is regarding your recommendation to follow a consistent checked v. unchecked policy in a given package. I can't find a justifcation for this in your book, and it's not obvious to me why this would be good practice. It seems like it restricts flexbility, and I can't see what it buys you. Thx.

    Regards,
    Steve Pearson

    PS I got tremendous value from your book. Thanks.
  101. I would not go as far as saying that checked exceptions is a failed experiment. They are very useful when you have resources you must free such as closing Connection or Stream objects.

    However we need to carefully think about whether a method should through a checked or unchecked exception. Is the error a programmer error, a configuration error or system error, the exception should probably be unchecked. Otherwise we need to think about how MOST of the calling code will deal with this error. This will give usually us a good indication as to whether the exception should be checked on unchecked.

    regards Malcolm
  102. I think I really need to proof read my posts more:

    <Proof-Read>
    I would not go as far as saying that checked exceptions are a failed experiment. They are very useful when you have resources you must free, such as closing Connection and I/O Stream objects.

    However, we need to carefully think about whether a method should throw checked or unchecked exceptions. If the method is error a programmer error, a configuration error or a system error, then the exception should probably be unchecked. Otherwise we need to think about how MOST of the calling code will deal with this error. This will usually give us a good indication as to whether the exception should be checked or unchecked.

    Most of the time in web applications I use unchecked exceptions, one year ago it would have been checked exceptions.

    Regards Malcolm
    </Proof-Read>
  103. Steven,

    <quote>
    My question is regarding your recommendation to follow a consistent checked v. unchecked policy in a given package. I can't find a justifcation for this in your book, and it's not obvious to me why this would be good practice. It seems like it restricts flexbility, and I can't see what it buys you.
    </quote>

    What I was trying to say is that it's important to respect conventions regarding exception usage in working on an existing code base. So "per project" might be a better way to put it than "per package". The scenario I was considering is where an existing code base uses checked exceptions exclusively. In this case, although you and I agree that using checked exceptions exclusively isn't how we would have designed the app in the first place, it would be important to ensure that any additional code behaved the same way as the existing code. If new code began to use unchecked exceptions more widely that might prove confusing when the modified application was maintained by programmers who had previously worked on it.

    Regards,
    Rod
  104. Got it. Thanks.