TryCatchRedo

From APIDesign

Revision as of 16:49, 1 February 2009 by JaroslavTulach (Talk | contribs)
(diff) ←Older revision | Current revision (diff) | Newer revision→ (diff)
Jump to: navigation, search

Often when thinking about exceptions, they are thought to be somewhat special, not really full featured classes. At least many coding practices advice to not use them in such and such situations. As a result developers often do not think about using inheritance or other object oriented techniques when dealing with exceptions. Sometimes this is justified, sometimes it is too restricting approach. In Java exceptions are just like any regular classes and this can sometimes be used to achieve surprising results.

All developers think about exceptions as something that can be thrown and caught. Some know that it is useful to call exceptions' getters to get more info about the failure represented by the exception. However only few explore design where exceptions also contain setters or other mutable methods. Not that it would make sense to modify state of exception, as that is short living object, however the exception can serve as bridge to some internal longer living object and can server as an interface that changes its state.

This imperative can be use to implement Try/Catch/Redo pattern. Imagine that some code deep inside of set of I/O operations cannot proceed without asking a question. For example the NetBeans version control modules may need to ask the user whether file shall be locked before allowing its content to be changed. For that purpose they may implement a special extended IOException:

does not exists: trycatchredo.UserQuestionException

This is just another IOException, so for clueless API users nothing changes. One can continue to write classical saving code:

does not exists: trycatchredo.SaveAction

However in case one needs to provide support for safe queries, one can extend the code to recognize the special exception and communicate with it:

does not exists: trycatchredo.SaveActionWithQuery

The confirm method is the callback to the internals of the URLConnection provider, like the NetBeans version control modules or this simple stream that can ask questions:

does not exists: trycatchredo.stream
Personal tools
buy