SOLID Principles · Coding problem
Smart Home Capabilities
A free coding problem from the Interface Segregation Principle skill. Read it here, then solve it in the app in Java or Python.
- Easy
- Coding problem
- Free
- Java and Python
The problem
A smart-home hub controls a lamp, a fan and a heater. It works out what each device can do by checking which small role interfaces it implements - Switchable, Dimmable, Heating - so it can reply "fan cannot dim" instead of sending a command the device can't handle.
The devices were written against an older fat interface, SmartDevice, which extends all three roles. So every device claims every capability and fills the gaps with methods that throw UnsupportedOperationException. The hub believes the fan can dim, tries it, and crashes into an error.
Apply the Interface Segregation Principle: remove the fat interface and let each device implement only the roles it really supports:
- lamp: switch and dim (brightness is kept between 0 and 100; dimming to 0 turns it off, dimming above 0 turns it on)
- fan: switch only
- heater: switch and heat (the target is kept between 10 and 30 degrees)
The existing behavior of each real capability must stay exactly as it is.
In Python: the roles are abstract base classes that the hub checks with isinstance, and the unsupported methods raise NotImplementedError (Java's UnsupportedOperationException).
Commands: ON <device>, OFF <device>, DIM <device> <percent>, HEAT <device> <celsius>, CAPS <device>, STATUS.
Example
Input:
5
CAPS lamp
CAPS fan
DIM fan 50
DIM lamp 40
STATUS
Output:
lamp: switch dim
fan: switch
fan cannot dim
lamp brightness 40%
lamp on 40%, fan off, heater off 20C
Constraints
- At most 1000 commands; device names are
lamp,fanandheater; numbers fit in anint.
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 Interface Segregation Principle
Solve it Smart Home Capabilities free
No card needed. Lessons, practice questions and easy problems are free forever.
Free plan, no card · 7-day Pro trial · Cancel anytime