educative.io

Is there a reason why State is an interface and not an abstract class?

Is there a reason why State is an interface and not an abstract class? In general, when do you choose interface over abstract class and vice versa?

Also I believe all the state functions should return a new state, instead of void. For example, calling VendingMachine’s function insertMoney() will invoke currentState’s insertMoney() and that should return a new state and we can set currentState to that new state. Let me know if you think this is incorrect? Thanks!


Course: Grokking the Low Level Design Interview Using OOD Principles - Learn Interactively
Lesson: Class Diagram for the Vending Machine - Grokking the Low Level Design Interview Using OOD Principles

Hi @Yunfei_Xie,

The State design pattern is used to allow an object to change its behavior based on its internal state, which is achieved through a State interface or abstract class. We can use an interface or abstract class both for this purpose. The State interface or abstract class defines the methods and properties common to all concrete states. Each concrete state class implements these methods and properties according to its specific behavior. Using an interface or abstract class in the State pattern provides a common interface for all states, allowing for flexibility and extensibility in the design and enabling objects to change their behavior based on their internal state.

Yes, you are right. It is good practice to have state functions return a new state object instead of directly modifying the current state object. This ensures that the current state object remains immutable, and any changes made to it are done through a new state object, making it easier to track state transitions and maintain the integrity of the state machine.

Note: We modified the current state object directly.

Happy Learning :slight_smile: