Junior — Middle+
Revision and improvement of the money transfer function in Kotlin
livecode
Task condition
This example shows a simple Kotlin function that transfers funds from one account to another. It is necessary to identify potential issues related to transactions and suggest ways to optimize or completely replace it.
fun transfer(sourceAccountId: Long, destinationAccountId: Long, transferAmount: Int) {
val sourceCurrentBalance = dao.getCurrentSum(sourceAccountId)
dao.updateSum(sourceAccountId, sourceCurrentBalance - transferAmount)
val destinationCurrentBalance = dao.getCurrentSum(destinationAccountId)
dao.updateSum(destinationAccountId, destinationCurrentBalance + transferAmount)
}
What could go wrong?
- Lack of sufficient funds check on the source account → possible negative balance.
- No validation of input parameters (negative amount, identical IDs).
- Read and write operations are not within a single atomic transaction → race conditions and loss of funds may occur under concurrent requests.
- Database access errors (exceptions) are not handled, which may lead to partial operation execution.
- No logging or audit trail, complicating debugging and monitoring.
Refactoring options:
- Wrap reading and updating balances in a single
SERIALIZABLElevel transaction or use anoptimistic lockingmechanism. - Add preliminary checks: sufficient funds, correctness of the amount, different accounts.
- Implement exception handling and transaction rollback on errors.
- Rewrite the function to return the operation result (
Result/Either) and/or throw specialized exceptions. - If necessary, move business logic to a separate service class, leaving database operations in DAO, which simplifies testing (mock objects).
- Add operation logging and record in an audit table.
Can this function be omitted? If the system already has a general financial operations mechanism (e.g., a payment service), then this function should be removed and replaced with a centralized API that already implements all the above checks and transactional integrity.