0

I am working on pset8 everything is working I have found a snippet of my code which is identical for buying and selling only difference is to subtract or add to current cash.

Can someone point me in the right direction on how to turn this into a function which can be used within both routes?

# Get current amount of cash person has --- BUY ---
user = db.execute("SELECT cash FROM users WHERE id = :user_id", user_id=user_id)
cash = user[0]["cash"]
total = shares * stock["price"]  # Calculate total value of shares purchased
new_cash = cash - total  # Deduct current purchase from current cash amount
now = time.strftime('%Y-%m-%d %H-%M-%S')

# Get current amount of cash person has --- SELL ---
user = db.execute("SELECT cash FROM users WHERE id = :user_id", user_id=user_id)
cash = user[0]['cash']
total = shares * stock["price"]  # Calculate total value of shares
new_cash = cash + total  # Add sale value to current cash amount
now = time.strftime('%Y-%m-%d %H-%M-%S')
1

I don't really see any practical reason or method to using the same function for both buy and sell. While there's overlap, the differences are enough that they should be separate functions. Combining them into the same function just leads to confusion if the code has to be modified later, or even while writing the current code!

Consider this. A buy requires only that the account has enough money to make the purchase. It doesn't care about how many shares of that stock are already owned. Conversely, a sell MUST check that the seller has enough shares, but doesn't care about the cash balance.

AFTER the cash or stock share balance is checked, both will need to be updated.

Since the cash balance and the number of shares are useful information for both buy and sell, a single function can be used to retrieve those balances. However, to change them, it would be better to write the appropriate buy code in one function and sell code in another.

Just my thoughts on the matter.

1
  • Thank's Cliff, very insightful as usual :)
    – Pierre
    Sep 30 '19 at 6:23

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .