Facebook Pixel

Exercise: SOLID Together

This exercise brings SRP, OCP, and DIP together in a single small program. You will implement a checkout system where each responsibility is isolated in its own class and adding a new payment method requires no changes to existing code.

Scenario

A checkout session holds a cart of items and supports payment through a registry of named payment methods. The session is driven by a sequence of commands, and each command produces exactly one output line.

Commands

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

CommandBehaviorOutput
["additem", price]Add an item with the given integer price to the cart"Added item (<price>)"
["total"]Report the running total of all prices added so far"Total: <sum>"
["pay", method]Pay using card or cash"Paid <total> via <method>", or "Cart empty" if no items, or "Unknown method: <method>" for unrecognized methods
Example
Input
7
additem 30
additem 20
total
pay card
pay cash
additem 10
pay bitcoin
Output
Added item (30)
Added item (20)
Total: 50
Paid 50 via card
Paid 50 via cash
Added item (10)
Unknown method: bitcoin
Explanation
Two items are added for a total of 50. Both `pay card` and `pay cash` succeed and each reports the current cart total — the cart is not cleared between payments. After adding a third item, `pay bitcoin` fails because "bitcoin" is not in the payment registry and returns "Unknown method".

Your task

Fill in add_item and total on Cart, and create the two payment classes below the PaymentMethod interface in the editor: CardPayment and CashPayment, each implementing pay. Do not modify PaymentMethod, the registry, or run_checkout.

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