SOLID Principles · Coding problem
Subscriptions on an Injected Clock
A free coding problem from the Dependency Inversion Principle skill. Read it here, then solve it in the app in Java or Python.
- Easy
- Coding problem
- Free
- Java and Python
The problem
Subscription rules depend on today's date - and code that reads the wall clock directly can't be tested: you'd have to wait 30 days to see a subscription expire. The fix is Dependency Inversion: the service depends on a Clock abstraction, and whoever creates it decides which clock to pass - SystemClock in production, a ManualClock in tests.
The starter's constructor receives a Clock but ignores it and reads the real time instead. Store the injected clock and implement the rules using only clock.today():
subscribe(user, days)- if the user is currently active, the new days are added to their existing expiry day; otherwise the subscription runs from today. Returns the new expiry day.- A user is active while
today < expiryDay. status(user)-never subscribed,active, <n> day(s) left,expired today(whentoday == expiryDay) orexpired <n> day(s) ago.activeUsers()- the names of active users in alphabetical order.
In Python: the methods are subscribe, status and active_users; Clock is an abstract base class (any object with a today() method would do), and the real clock reads time.time().
Commands: SUBSCRIBE <user> <days>, ADVANCE <days> (moves the test clock forward; it starts at day 0), STATUS <user>, ACTIVE.
Example
Input:
6
SUBSCRIBE asha 30
ADVANCE 10
STATUS asha
ADVANCE 20
STATUS asha
STATUS ravi
Output:
asha active until day 30
day 10
asha active, 20 day(s) left
day 30
asha expired today
ravi never subscribed
Constraints
- At most 1000 commands;
1 <= days <= 10^6.
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 Dependency Inversion Principle
Solve it Subscriptions on an Injected Clock free
No card needed. Lessons, practice questions and easy problems are free forever.
Free plan, no card · 7-day Pro trial · Cancel anytime