Posted under EJB
Permalink
Tags CommandPattern, EJB, Tip, Tutorial
Exceptions are hotly debated on line, as is this issue as to whether to return status or throw an exception. There is no straight answer for all cases, but for the projects I am working on, I am adopting the following.
- Many EJB methods return data as lists of entities for example, and to return a status code as well is a nuisance as you need to build a wrapper class for this.
- My present way forward therefore is to throw exceptions in the EJB methods, for example when you attempt to delete a non existent row.
- Even though some methods like delete have no return and could return a status, others do return data and could not easily do it this way. I prefer to be consistent in my approach.
- Therefore, I will throw checked exceptions for these ‘important’ ones like non existant data, that the caller should check for.
- If I am using a command pattern as per my post on this here, I will then catch these in the command objects, and convert to one of the status enum values I have proposed for my Command Pattern implementation. This is an ideal place to do it, exceptions are not friendly to the command pattern mechanism if you want to continue from one, and I have already added the generic status enum idea.
- For cases when I do not use command patterns, a similar approach could be used by catching the exceptions in the model layer and converting to a status enum there. My model layer is stateful, and typically my fetch methods in the model populate result properties and then return void. These would be ideally placed to catch any exceptions from the service layer and return a status enum instead (or just return the enum status from a command if that was used).
- Coupling and isolation of the status enum needs to be considered. Where the enum is defined in the model, the view/controller layer has no dependency on the service layer. However, if the enum were to be defined in the service layer, the view then has a dependency on it as it uses that enum. This is (perhaps to a lesser extent) also true if the enum is defined in a command class, as these are also service layer classes. I may therefore decide to map them to a model specific enum (which may be similar).