Home > Software engineering >  which of these structure is better?
which of these structure is better?

Time:12-12

I'm working on a project in python and i have thought in two ways to write the same code but i want to know which structure is better in performance, semantically and Best Practices.

version 1

if x == 1:
    try:
        order = cliente.order_market_buy(
                symbol = moeda,
                quoteOrderQty=quantidade)
        print(f'buy {order}')

    except Exception as erro:
        print(erro.status_code)
        print(erro.response)
        print(erro.code)
        print(erro.message)
        print(erro.request)
        if erro.code == -2010:
            print('no money')


elif x == -1:
    try:
        order = cliente.order_market_sell(
                symbol = moeda,
                quantity=quantidade)
        print(f'sell {order}')

    except Exception as erro:
        print(erro.status_code)
        print(erro.response)
        print(erro.code)
        print(erro.message)
        print(erro.request)
        if erro.code == -2010:
            print('no crypto')

version 2

try:
    if x == 1:
        order = cliente.order_market_buy(
                symbol = moeda,
                quoteOrderQty=quantidade)
        print(f'buy {order}')

    elif x == -1:
        order = cliente.order_market_sell(
                symbol = moeda,
                quantity=quantidade)
        print(f'sell {order}')


except Exception as erro:
        print(erro.status_code)
        print(erro.response)
        print(erro.code)
        print(erro.message)
        print(erro.request)
        if erro.code == -2010:
            if x == 1:
                print('no money')
            elif x == -1:
                print('no crypto')

both codes do the same thing, but, the first is easiest to debug, and the second is smaller and cleaner. Both take the same time to run.

is there another better way to write this?

CodePudding user response:

Having one exception block is preferable IMO if it's doing roughly the same thing in all cases. Here's how you could avoid having to repeat the if x check:

try:
    if x == 1:
        currency = "money"
        order = cliente.order_market_buy(
            symbol=moeda,
            quoteOrderQty=quantidade
        )
        print(f'buy {order}')
    elif x == -1:
        currency = "crypto"
        order = cliente.order_market_sell(
            symbol=moeda,
            quantity=quantidade
        )
        print(f'sell {order}')
except Exception as erro:
        print(erro.status_code)
        print(erro.response)
        print(erro.code)
        print(erro.message)
        print(erro.request)
        print(f'no {currency}')
  • Related