Skip to content

Add solution for Challenge 7 by shansing#1435

Open
shansing wants to merge 6 commits intoRezaSi:mainfrom
shansing:challenge-7-shansing
Open

Add solution for Challenge 7 by shansing#1435
shansing wants to merge 6 commits intoRezaSi:mainfrom
shansing:challenge-7-shansing

Conversation

@shansing
Copy link
Contributor

Challenge 7 Solution

Submitted by: @shansing
Challenge: Challenge 7

Description

This PR contains my solution for Challenge 7.

Changes

  • Added solution file to challenge-7/submissions/shansing/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 Feb 26, 2026

Walkthrough

Adds a new Go file implementing a concurrency-safe BankAccount type with ID, Owner, Balance, MinBalance, a MaxTransactionAmount constant, custom error types, a NewBankAccount constructor, and Deposit/Withdraw/Transfer methods using mutexes and deterministic lock ordering and validations.

Changes

Cohort / File(s) Summary
Bank Account Implementation
challenge-7/submissions/shansing/solution-template.go
New file: introduces BankAccount (ID, Owner, Balance, MinBalance, unexported mu), MaxTransactionAmount constant, error types (AccountError, InsufficientFundsError, NegativeAmountError, ExceedsLimitError), NewBankAccount constructor with validations, and methods Deposit, Withdraw, Transfer with mutex-based concurrency control, deterministic lock ordering, and balance checks.

Sequence Diagram

sequenceDiagram
    participant Client
    participant Source as BankAccount (Source)
    participant Target as BankAccount (Target)

    Client->>Source: Transfer(amount, target)
    Source->>Source: validate amount & limits

    alt Lock ordering by ID
        Source->>Source: Lock mu (lower ID first)
        Source->>Target: Lock target.mu (higher ID second)
    end

    Source->>Source: compute new source balance
    Source->>Target: compute new target balance
    Source->>Source: validate balances (min, max)
    alt success
        Source->>Source: apply source balance
        Source->>Target: apply target balance
        Source->>Source: unlock mu
        Source->>Target: unlock target.mu
        Source-->>Client: return nil
    else failure
        Source->>Source: unlock mu
        Source->>Target: unlock target.mu
        Source-->>Client: return error
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Poem

I hop through code with nimble paws,
Locks click softly without a pause,
Balances safe, transfers true,
Minted carrots—ledger new! 🐇✨

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly references the main change: adding a solution for Challenge 7 by a specific user, matching the PR's primary objective.
Description check ✅ Passed The description is directly related to the changeset, explaining that it contains a Challenge 7 solution submission with the specific file added and testing validation.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


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: 2

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

127-143: Remove duplicate unreachable validations in Withdraw and Transfer.

amount is already validated before locking. Re-checking it later adds dead code and maintenance noise.

♻️ Proposed cleanup
 func (a *BankAccount) Withdraw(amount float64) error {
@@
 	if err := checkBalance(newBalance, a.MinBalance); err != nil {
 		return err
 	}
-	if amount > MaxTransactionAmount {
-		return &ExceedsLimitError{}
-	}
 	a.Balance = newBalance
 	return nil
 }
@@
 	a.Balance = aBalance
 	target.Balance = targetBalance
-	if amount > MaxTransactionAmount {
-		return &ExceedsLimitError{}
-	}
-	if amount < 0 {
-		return &NegativeAmountError{}
-	}
 	return nil
 }

Also applies to: 180-185


18-19: Clean up commented-out scaffolding before merge.

Commented code and duplicated placeholder text (Line 107) make the solution harder to read and review.

Also applies to: 73-75, 95-102, 107-107


ℹ️ Review info

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a7ac764 and e99d5b9.

📒 Files selected for processing (1)
  • challenge-7/submissions/shansing/solution-template.go

Refactor locking mechanism for account transactions.
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: 2

🧹 Nitpick comments (1)
challenge-7/submissions/shansing/solution-template.go (1)

86-92: Variable BankAccount shadows the type name.

Using the same identifier for the variable and the type can cause confusion. Consider renaming to account or bankAccount.

♻️ Suggested rename
-	BankAccount := &BankAccount{
+	account := &BankAccount{
 		ID:         id,
 		Owner:      owner,
 		Balance:    balance,
 		MinBalance: minBalance,
 	}
-	return BankAccount, nil
+	return account, nil

ℹ️ Review info

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e99d5b9 and fd97131.

📒 Files selected for processing (1)
  • challenge-7/submissions/shansing/solution-template.go

shansing and others added 3 commits February 26, 2026 10:14
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
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

♻️ Duplicate comments (3)
challenge-7/submissions/shansing/solution-template.go (3)

161-172: ⚠️ Potential issue | 🔴 Critical

Guard target before dereferencing to prevent panic.

Line 161 reads target.ID before verifying target != nil; Transfer(..., nil) will panic.

🐛 Proposed fix
 func (a *BankAccount) Transfer(amount float64, target *BankAccount) error {
 	// Implement transfer functionality with proper error handling
+	if target == nil {
+		return &AccountError{}
+	}
 	if amount > MaxTransactionAmount {
 		return &ExceedsLimitError{}
 	}

191-200: ⚠️ Potential issue | 🟠 Major

checkBalance is mixing balance validity with transaction-limit policy.

balance > MaxTransactionAmount at Line 198 makes account state invalid based on total balance, not transaction amount. This incorrectly affects constructor, deposit, and transfer target validations.

✅ Proposed fix
 func checkBalance(balance float64, minBalance float64) error {
 	if balance < 0 {
 		return &NegativeAmountError{}
 	}
 	if balance < minBalance {
 		return &InsufficientFundsError{}
 	}
-	if balance > MaxTransactionAmount {
-		return &ExceedsLimitError{}
-	}
 	return nil
 }

141-147: ⚠️ Potential issue | 🟡 Minor

Remove duplicated checks/assignments (dead code).

There are duplicated checkBalance/return and duplicated balance assignments. These are no-op repeats and increase bug surface.

🧹 Proposed cleanup
 func (a *BankAccount) Withdraw(amount float64) error {
@@
 	newBalance := a.Balance - amount
 	if err := checkBalance(newBalance, a.MinBalance); err != nil {
 		return err
 	}
-	if err := checkBalance(newBalance, a.MinBalance); err != nil {
-		return err
-	}
 	a.Balance = newBalance
 	return nil
-	a.Balance = newBalance
-	return nil
 }
@@
 	a.Balance = aBalance
 	target.Balance = targetBalance
-	a.Balance = aBalance
-	target.Balance = targetBalance
 	return nil
 }

Also applies to: 182-185


ℹ️ Review info

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between fd97131 and 3388085.

📒 Files selected for processing (1)
  • challenge-7/submissions/shansing/solution-template.go

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.

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

148-168: ⚠️ Potential issue | 🔴 Critical

Nil pointer dereference: target accessed before validation.

Line 156 accesses target.ID without first checking if target is nil. This will cause a panic if Transfer is called with a nil target.

🐛 Proposed fix
 func (a *BankAccount) Transfer(amount float64, target *BankAccount) error {
 	// Implement transfer functionality with proper error handling
+	if target == nil {
+		return &AccountError{}
+	}
 	if amount > MaxTransactionAmount {
 		return &ExceedsLimitError{}
 	}
🧹 Nitpick comments (2)
challenge-7/submissions/shansing/solution-template.go (2)

86-92: Variable name shadows type name.

The local variable BankAccount shadows the struct type BankAccount. This compiles but can cause confusion and makes the code harder to read.

♻️ Suggested fix
-	BankAccount := &BankAccount{
+	account := &BankAccount{
 		ID:         id,
 		Owner:      owner,
 		Balance:    balance,
 		MinBalance: minBalance,
 	}
-	return BankAccount, nil
+	return account, nil

95-102: Consider removing commented-out code.

The commented getAccountById function appears to be unused remnant code. If not needed for reference, removing it improves readability.


ℹ️ Review info

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3388085 and f30f351.

📒 Files selected for processing (1)
  • challenge-7/submissions/shansing/solution-template.go

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant