OOP Fundamentals · Coding problem

An Account That Protects Its Own Rules

A free coding problem from the Encapsulation & Immutability skill. Read it here, then solve it in the app in Java or Python.

  • Easy
  • Coding problem
  • Free
  • Java and Python

The problem

Implement Account so that nothing outside the class can break its rules:

  • deposit(amount) - amount must be positive, else throw IllegalArgumentException("amount must be positive"). Records deposit <amount> in the history.
  • withdraw(amount) - amount must be positive (same error). If the withdrawal would take the balance below -overdraftLimit, throw IllegalStateException("overdraft limit exceeded") and change nothing. Records withdraw <amount>.
  • balance() - the current balance.
  • history() - the list of recorded operations. Callers must not be able to change the account's history through this list.

The TAMPER command plays a hostile caller that tries to clear the list it gets back and add hacked. If your account is properly encapsulated, the next HISTORY is unaffected.

In Python: raise ValueError("amount must be positive") and RuntimeError("overdraft limit exceeded"). Python has no private: the account's own list is self._history (a leading underscore marks it internal by convention), and history() must not return it.

Commands: NEW <overdraftLimit>, DEPOSIT <n>, WITHDRAW <n>, BALANCE, HISTORY, TAMPER.

Example

Input:
5
NEW 50
DEPOSIT 100
WITHDRAW 140
TAMPER
HISTORY

Output:
overdraft limit 50
balance 100
balance -40
tamper attempted
history [deposit 100, withdraw 140]

Constraints

  • At most 1000 commands; amounts fit in a long.

How it's graded

  • Run checks your code against the examples. Submit also runs hidden tests, and you see pass or fail for them, never their inputs.
  • Stuck? Hints come in four steps, from a nudge to a code skeleton, each costing part of the points.
  • Once you pass, you see the approaches from brute force to optimal, and where your solution lands among them.

More problems in Encapsulation & Immutability

Solve it An Account That Protects Its Own Rules free

No card needed. Lessons, practice questions and easy problems are free forever.

Free plan, no card · 7-day Pro trial · Cancel anytime