Facebook Pixel

Exercise: Law of Demeter

This exercise applies the Law of Demeter. You will build a billing system where one object never reaches through another to touch a third.

Scenario

A Biller charges Customer objects. Each Customer owns a private Wallet. The Biller calls customer.pay(amount) and receives a boolean result — it never calls customer.getWallet().deduct(amount) or reads the wallet balance directly. Only Customer touches its own Wallet. The biller is driven by a sequence of commands.

Commands

The program reads a list of commands, one per line, and prints one line of output per command.

CommandBehaviorOutput
["customer", name, cash]Register a new customer with the given integer cash balance"Added <name>"
["charge", name, amount]Attempt to charge the named customer"Charged <amount>, <name> has <remaining>" on success, "<name> cannot afford" if insufficient, or "<name> not found" if unknown
Example
Input
6
customer Alice 100
customer Bob 30
charge Alice 40
charge Bob 50
charge Alice 80
charge Ghost 10
Output
Added Alice
Added Bob
Charged 40, Alice has 60
Bob cannot afford
Alice cannot afford
Ghost not found
Explanation
Alice starts with 100 and Bob with 30. The first charge deducts 40 from Alice, leaving 60. Bob cannot afford 50 so the charge is declined. Alice then tries to pay 80 but has only 60 remaining, so that charge is also declined. The final command names a customer who was never registered.

Your task

Implement Wallet.pay and Wallet.balance, then implement Customer.pay and Customer.balance as delegating wrappers, and finally fill in Biller.charge so it calls only customer methods.

Invest in Yourself
Your new job is waiting. 83% of people that complete the program get a job offer. Unlock unlimited access to all content and features.
Go Pro