mardi 25 juin 2019

Which is worse - duplicated code or double try/except?

I have a situation where I want to do multiple things while handling an exception. Since I want to make this about the general case, I'll translate my specific case into some more general language.

When I have an exception in this piece of code, I want to:

  1. Always perform a rollback-style operation
  2. If it is an application specific exception, I want to perform some logging and swallow the exception.

So I can think of two ways to solve it, both ugly:

# Method nested-try/except block
try:
    try:
        do_things()
    except:
        rollback()
        raise
except SpecificException as err:
    do_advanced_logging(err)
    return

# Method Duplicate Code
try:
    do_things()
except SpecificException as err:
    rollback()
    do_advanced_logging(err)
    return
except:
    rollback()
    raise

Both will have the same behaviour.

I'm tending towards the nested try/except solution myself. While it might be slightly slower, I don't think the speed difference is relevant here - at the very least not for my specific case. Duplication of code is something I want to avoid also because my rollback() statement is slightly more involved that just a database rollback, even if it has the exact same purpose (it involves a web-API).

Is there a third option I haven't spotted that is better? Or is the duplicate code method better? Please note that the rollback() functionality is already factored out as much as possible, but still contains a function call and three arguments which includes a single hardcoded string. Since this string is unique, there's no reason to make it a named constant.

Aucun commentaire:

Enregistrer un commentaire