Design a Bank Account OOP Simulation with Transfers, Payments, and Merges
RampSoftware Engineer · Technical ScreenLast updated
This problem tests your ability to design a robust object-oriented system that enforces financial invariants (no negative balances, atomic transfers) and handles complex object lifecycle management like merging accounts.
Problem Statement
Design a simple banking system that manages Account objects. Your system should support the following operations while maintaining data integrity:
deposit(amount): Adds funds to an account.withdraw(amount): Removes funds, ensuring the balance never drops below zero.transfer(target_account, amount): Moves funds from the current account to a target account. This must be atomic.merge(other_account): Moves the entire balance ofother_accountinto the current account, then closes theother_account(setting its balance to 0 and marking it as inactive).
Requirements
- Ensure thread safety for concurrent operations.
- Prevent illegal states, such as transferring money to a closed account or attempting to merge an account into itself.
- Implement a unique
account_idfor every account instance.
Expected Interface
class Account:
def __init__(self, account_id, initial_balance=0.0):
# Initialize account properties
pass
def deposit(self, amount):
# Logic to add funds
pass
def withdraw(self, amount):
# Logic to subtract funds (must return False if insufficient funds)
pass
def transfer(self, target_account, amount):
# Logic to move funds to target_account
pass
def merge(self, other_account):
# Move all funds from other_account to self and close other_account
pass
Example
acc1 = Account("A", 100)
acc2 = Account("B", 50)
acc1.transfer(acc2, 30)
# acc1 balance: 70, acc2 balance: 80
acc1.merge(acc2)
# acc1 balance: 150, acc2 balance: 0, acc2 status: inactive
Edge Cases
- Transferring more money than available.
- Attempting to merge an account that is already closed.
- Thread-safety during simultaneous operations on the same two accounts.
Hints
Hint 1
Use a lock or mutex mechanism to ensure that balance modifications remain atomic across operations like transfers.
Hint 2
When implementing `merge`, ensure you acquire locks for both accounts in a consistent order to prevent deadlocks.
Hint 3
Consider using an `is_active` boolean flag to track whether an account is closed and prevent further transactions.
Follow-up questions
- How would you log these operations for an audit trail while ensuring the logging operation doesn't introduce consistency bugs?
- What changes would be required to support multi-currency accounts?
- How would you handle an 'undo' or 'rollback' requirement if a transfer fails halfway through due to an external system error?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.