Add account balance transfer
Problem Context
Users need to transfer money between their accounts. The system must ensure balance never goes negative.
Expert
300 points
File Changes (1)
src/main/java/com/example/service/AccountService.java
MODIFIED
@@ -25 +25 @@
| 25 | 25 | @Transactional |
| 26 | + public void transfer(Long fromAccountId, Long toAccountId, BigDecimal amount) { |
|
| 27 | + Account fromAccount = accountRepository.findById(fromAccountId) |
|
| 28 | + .orElseThrow(() -> new AccountNotFoundException(fromAccountId)); |
|
| 29 | + Account toAccount = accountRepository.findById(toAccountId) |
|
| 30 | + .orElseThrow(() -> new AccountNotFoundException(toAccountId)); |
|
| 31 | + |
|
| 32 | + // Check if sender has sufficient balance |
|
| 33 | + if (fromAccount.getBalance().compareTo(amount) < 0) { |
|
| 34 | + throw new InsufficientBalanceException(fromAccountId); |
|
| 35 | + } |
|
| 36 | + |
|
| 37 | + // Perform transfer |
|
| 38 | + fromAccount.setBalance(fromAccount.getBalance().subtract(amount)); |
|
| 39 | + toAccount.setBalance(toAccount.getBalance().add(amount)); |
|
| 40 | + |
|
| 41 | + accountRepository.save(fromAccount); |
|
| 42 | + accountRepository.save(toAccount); |
|
| 43 | + } |
|
| 26 | 44 | } |
Login Required: You must be registered to submit reviews and receive AI feedback.
Register or
login to start reviewing!
Your Review
Review Tips
- Look for security vulnerabilities (SQL injection, XSS, etc.)
- Check for null pointer exceptions and error handling
- Consider performance implications
- Evaluate code maintainability and readability
- Check for proper resource management
- Look for logic errors or edge cases