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.
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:
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With