Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programming Style: Try Catch and External Dependents

Tags:

java

I have a simple style question. In an application that I am writing there are several class methods that include a try/catch block as well as function external to the block that depends on the result of the block. For example (in psudo code):

try {
   start_transaction;
   persist_data;
   stop_transaction;
}
catch {
   rollback_transaction;
}
finally {
}

if (transaction_successful)
   send_message;

The only way I can think of for testing if the transaction is successful would be to set a method variable flag in the try catch block and then test it in the if statement. Of course this would work, however I am curious to know what the conventional "wisdom" is with this? Maybe "send_message" should be in the try catch block although this may be unneccessary clutter? I guess this is a fairly straight forward question - just trying to ensure my code is well structured / organised.

like image 610
skyman Avatar asked Apr 19 '26 20:04

skyman


2 Answers

It seems that you need to think a little bit more on the proper layering of your software/increasing of a cohesion for this class/method. From the provided example it seems that here you have DAL/business Layer mix (persistense + some business activities), that's the primary reason you need to react on the result of the transaction in the same method, right after the catch block.

With proper layering it could look like the following:

  • Persistence fails, you indicating this fact by throwing checked/runtime exception to the calling layer (it's up to you to decide how to indicate the failure exactly, depdends on your architectural approach),
  • Calling class catches the exception and does error handling - or sends the message in corresponding try block right after the call of the 'persisting' method

Of course you could set the flag (as you've suggested) and use AOP advise to process such situations (esp. in case if 'send_message' is auxiliary function).

like image 172
71taa Avatar answered Apr 21 '26 08:04

71taa


It'll be simple enough to put it in the try block. "Cluttered code" is a matter of personal preference but this keeps things simple.

like image 34
SomeKittens Avatar answered Apr 21 '26 09:04

SomeKittens



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!