Skip to content

Conversation

@kiramux
Copy link
Contributor

@kiramux kiramux commented Nov 11, 2025

Challenge 7 Solution

Submitted by: @kiramux
Challenge: Challenge 7

Description

This PR contains my solution for Challenge 7.

Changes

  • Added solution file to challenge-7/submissions/kiramux/solution-template.go

Testing

  • Solution passes all test cases
  • Code follows Go best practices

Thank you for reviewing my submission! 🚀

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Nov 11, 2025

Walkthrough

Adds a new Go implementation of a concurrency-safe BankAccount type with validations, custom error types, a MaxTransactionAmount constant, a constructor, and Deposit/Withdraw/Transfer methods using mutexes and deterministic ID-based lock ordering for transfers.

Changes

Cohort / File(s) Change Summary
Bank Account Implementation
challenge-7/submissions/kiramux/solution-template.go
New file adding BankAccount (ID, Owner, Balance, MinBalance, mutex), MaxTransactionAmount, error types (AccountError, InsufficientFundsError, NegativeAmountError, ExceedsLimitError), NewBankAccount constructor with validations, and methods Deposit, Withdraw, Transfer with parameter checks, mutex-protected balance updates, and deterministic ID-based lock ordering for transfers.

Sequence Diagram(s)

sequenceDiagram participant Client participant Account as BankAccount participant Mu as account.mu Client->>Account: Deposit(amount) activate Account Account->>Account: Validate amount (>=0 && <= MaxTransactionAmount) alt invalid Account-->>Client: error else valid Account->>Mu: Lock activate Mu Account->>Account: Balance += amount Mu-->>Account: Unlock deactivate Mu Account-->>Client: nil end deactivate Account 
Loading
sequenceDiagram participant Client participant Src as SourceAccount participant Tgt as TargetAccount participant MuSrc as src.mu participant MuTgt as tgt.mu Client->>Src: Transfer(amount, Tgt) activate Src Src->>Src: Validate amount, limits, target (non-nil, not self) alt invalid Src-->>Client: error else valid Note over Src,Tgt: Determine lock order by account ID (deterministic) Src->>MuSrc: Lock (first) activate MuSrc Tgt->>MuTgt: Lock (second) activate MuTgt Src->>Src: Balance -= amount Tgt->>Tgt: Balance += amount MuTgt-->>Tgt: Unlock deactivate MuTgt MuSrc-->>Src: Unlock deactivate MuSrc Src-->>Client: nil end deactivate Src 
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

  • Inspect Transfer locking order and all early-return/error paths for proper lock release.
  • Verify constructor parameter validation and error types/contents.
  • Confirm Withdraw enforces MinBalance and MaxTransactionAmount and that mutex protects all balance mutations.

Possibly related PRs

Pre-merge checks

✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the main change: adding a solution for Challenge 7 by a specific contributor.
Description check ✅ Passed The description is clearly related to the changeset, providing context about the challenge submission and confirming testing and code quality standards.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9bc7c2f and 95d99c8.

📒 Files selected for processing (1)
  • challenge-7/submissions/kiramux/solution-template.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • challenge-7/submissions/kiramux/solution-template.go

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 14d1f5f and a38df2f.

📒 Files selected for processing (1)
  • challenge-7/submissions/kiramux/solution-template.go (1 hunks)
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🧹 Nitpick comments (2)
challenge-7/submissions/kiramux/solution-template.go (2)

78-78: Replace Chinese comments with English.

The inline comments use Chinese characters, which may reduce readability for international contributors.

Apply this diff:

-// 验证 accountID +// Validate account ID	if id == "" {	...	} -// 验证 owner +// Validate owner	if owner == "" {	...	} -// 验证 initialBalance +// Validate initial balance	if initialBalance < 0 {	...	} -// 验证 minBalance +// Validate minimum balance	if minBalance < 0 {	...	} -// 比较 initialBalance 和 minBalance +// Check that initial balance meets minimum requirement	if initialBalance < minBalance {	...	}

Also applies to: 87-87, 96-96, 105-105, 114-114


205-205: Fix typo in comment.

"targer" should be "target".

Apply this diff:

-// check targer account is valid or not +// check target account is valid or not	switch target {
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a38df2f and f68b7ed.

📒 Files selected for processing (1)
  • challenge-7/submissions/kiramux/solution-template.go (1 hunks)
🔇 Additional comments (1)
challenge-7/submissions/kiramux/solution-template.go (1)

236-247: LGTM!

The balance transfer logic correctly validates the source account's minimum balance constraint and updates both account balances under proper locking.

1. fix error code mistakes of 'check minBalance' and 'Withdraw' 2. add defensive programming for duplicate IDs. maybe `a.ID == target.ID` but `a != target (duplicate IDs)`
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

♻️ Duplicate comments (1)
challenge-7/submissions/kiramux/solution-template.go (1)

11-17: Exported Balance/MinBalance fields still create race conditions.

This issue was previously flagged: exported Balance and MinBalance fields allow direct read/write access without mutex protection, causing potential data races with concurrent Deposit/Withdraw/Transfer operations.

🧹 Nitpick comments (2)
challenge-7/submissions/kiramux/solution-template.go (2)

78-114: Use English for code comments.

The validation logic is solid, but comments on lines 78, 87, 96, 105, and 114 are in Chinese. For consistency and broader accessibility, please use English comments throughout the codebase.

Apply this diff to translate the comments:

-// 验证 accountID +// Validate account ID	if id == "" {	return nil, &AccountError{	Code: "INVALID_ACCOUNT_ID",	Message: "account ID cannot be empty",	AccountID: id,	}	} -// 验证 owner +// Validate owner	if owner == "" {	return nil, &AccountError{	Code: "INVALID_OWNER",	Message: "owner name cannot be empty",	AccountID: id,	}	} -// 验证 initialBalance +// Validate initial balance	if initialBalance < 0 {	return nil, &NegativeAmountError{	Code: "INVALID_INITIAL_BALANCE",	Message: "initial balance cannot be negative",	Amount: initialBalance,	}	} -// 验证 minBalance +// Validate minimum balance	if minBalance < 0 {	return nil, &NegativeAmountError{	Code: "INVALID_MIN_BALANCE",	Message: "min balance cannot be negative",	Amount: minBalance,	}	} -// 比较 initialBalance 和 minBalance +// Compare initial balance and minimum balance	if initialBalance < minBalance {

207-212: Improve error message grammar.

The error message "target account is not existed" should be "target account does not exist" or "target account is nil" for better English grammar.

Apply this diff:

	case nil:	return &AccountError{	Code: "INVALID_TARGET_ACCOUNT", -Message: "target account is not existed", +Message: "target account does not exist",	AccountID: "",	}
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f68b7ed and a1bfc25.

📒 Files selected for processing (1)
  • challenge-7/submissions/kiramux/solution-template.go (1 hunks)
🔇 Additional comments (5)
challenge-7/submissions/kiramux/solution-template.go (5)

1-8: LGTM!

The package declaration and imports are appropriate for the bank account implementation with concurrency support.


19-22: LGTM!

The MaxTransactionAmount constant is well-defined and provides a clear transaction limit.


24-71: LGTM!

The custom error types are well-designed with clear fields and informative Error() methods that provide good context for debugging.


131-153: LGTM!

The Deposit method correctly validates the amount and uses mutex protection for thread-safe balance updates.


221-241: LGTM!

The deterministic lock ordering by account ID effectively prevents deadlocks, and the equal-ID case is now properly handled with a clear error message.

1. fix the typo in line 205:"targer" should be "target" 2. fix error code of 'withdraw' or 'transfer'. When withdraw or transfer, the error code "INVALID_TRANSFER_AMOUNT" is misleading here. This code suggests the amount parameter is invalid, but the actual issue is insufficient funds. Use "INSUFFICIENT_FUNDS" or "BELOW_MIN_BALANCE" for clarity.
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

♻️ Duplicate comments (1)
challenge-7/submissions/kiramux/solution-template.go (1)

11-17: Exported Balance fields still create race conditions.

The Balance and MinBalance fields remain exported, allowing external code to read/write them without acquiring the mutex. This races with the Deposit/Withdraw/Transfer methods. This issue was flagged in a previous review.

If the test harness requires these fields to be exported, document that direct field access is unsafe. Otherwise, make them private and provide thread-safe getter methods.

🧹 Nitpick comments (2)
challenge-7/submissions/kiramux/solution-template.go (2)

78-114: Consider using English for all comments.

The inline comments are written in Chinese (e.g., "验证 accountID" means "validate accountID"). For consistency and broader accessibility, consider translating them to English.

Apply this diff if desired:

-// 验证 accountID +// Validate account ID	if id == "" {	return nil, &AccountError{	Code: "INVALID_ACCOUNT_ID",	Message: "account ID cannot be empty",	AccountID: id,	}	} -// 验证 owner +// Validate owner	if owner == "" {	return nil, &AccountError{	Code: "INVALID_OWNER",	Message: "owner name cannot be empty",	AccountID: id,	}	} -// 验证 initialBalance +// Validate initial balance	if initialBalance < 0 {	return nil, &NegativeAmountError{	Code: "INVALID_INITIAL_BALANCE",	Message: "initial balance cannot be negative",	Amount: initialBalance,	}	} -// 验证 minBalance +// Validate minimum balance	if minBalance < 0 {	return nil, &NegativeAmountError{	Code: "INVALID_MIN_BALANCE",	Message: "min balance cannot be negative",	Amount: minBalance,	}	} -// 比较 initialBalance 和 minBalance +// Compare initial balance and minimum balance	if initialBalance < minBalance {

115-121: Consider using consistent error code naming.

The error code "INSUFFICIENT_FUND" (singular) is used here, while line 178 and 246 use "INSUFFICIENT_FUNDS" (plural). Consider using "INSUFFICIENT_FUNDS" consistently throughout for better maintainability.

Apply this diff for consistency:

	if initialBalance < minBalance {	return nil, &InsufficientFundsError{ -Code: "INSUFFICIENT_FUND", +Code: "INSUFFICIENT_FUNDS",	Message: fmt.Sprintf("the initialBalance: %.2f is less than minBalance: %.2f", initialBalance, minBalance),	MinBalance: minBalance,	}	}
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a1bfc25 and 9bc7c2f.

📒 Files selected for processing (1)
  • challenge-7/submissions/kiramux/solution-template.go (1 hunks)
🔇 Additional comments (8)
challenge-7/submissions/kiramux/solution-template.go (8)

1-8: LGTM!

Clean package structure with appropriate imports for error handling and concurrency control.


20-22: LGTM!

Transaction limit constant is well-defined and consistently applied across all monetary operations.


27-71: LGTM!

Well-designed error types with descriptive messages and appropriate context. Each error provides sufficient information for debugging and user feedback.


133-153: LGTM!

The deposit method correctly validates input and uses proper mutex synchronization for thread safety.


158-185: LGTM!

The withdraw method properly validates inputs, enforces minimum balance constraints, and correctly synchronizes balance updates. All previous issues have been addressed.


190-219: LGTM!

Comprehensive validation of transfer parameters including amount bounds, nil target, and self-transfer prevention. All previous issues have been corrected.


221-236: LGTM!

Excellent deadlock prevention implementation using deterministic lock ordering. The equal-ID edge case is now properly handled as suggested in the previous review.


238-254: LGTM!

Proper dual-lock acquisition with correct defer ordering, thorough balance validation, and atomic transfer execution. The implementation correctly prevents race conditions during transfers.

@RezaSi RezaSi merged commit 93a641d into RezaSi:main Nov 13, 2025
5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

2 participants