Vending Machine design — A State design pattern approach

Animesh Gaitonde
Nov 17, 2019 · 6 min read

Designing a Vending Machine software using the State design pattern

Vending Machine

Introduction

However, I knew the theory well & thanks to the book ‘Cracking the Coding Interview, I had understood the approach to tackle a software design interview question. In this article, I’ll walk you through the journey of how I started with a naive solution, improved the design, & finished off with a clean, modular and readable code.

Problem Statement

After all the clarification, the expectation was to build software the could store items (track the inventory), accept cash, & dispense items. Additionally, the interviewer wanted the design and code to be extensible, reusable & modular.

Vending Machine

Requirements

  • Vending Machine must keep track of the inventory
  • A person should be able to insert cash into the machine & choose an item
  • The Machine should confirm the inserted cash with the price of the selected item
  • The machine must display an error in case of insufficient cash or unavailable item
  • Finally, if all the above steps succeed then the user gets the selected item

Design

If you think of buying an item like a transaction, the machine only processes one transaction at a time. For eg: If the machine is in the process of dispensing an item, then the user can’t insert cash and try to buy another item. After the machine dispenses the item, the user can buy a new item.

In simple words, a user can buy a new item by either aborting or completing the existing transaction. To solve this we can define different states of the Vending Machine. Depending on the request, either the machine can change it’s state or stay in the same state.

Vending Machine States

States

  • Ready — Machine ready to accept cash
  • CashCollected — Machine has collected cash & user can now select the product or cancel the transaction
  • DispenseChange — Give back the change to the user
  • DispenseItem — Dispense the item upon successful validation of entered cash & the price of the selected item in inventory
  • TransactionCancelled — If the user cancels the transaction, return the cash given by the user
Vending Machine State Transitions

Initial Code

The class ‘VendingMachine’ exposed different methods to the user for interaction. Further, it encapsulated all the business logic to process the user commands. The code looked clumsy to me & I was sure the Interviewer would ask me a difficult question.

On taking a look, the Interviewer’s first question was ‘Does your design confirm to the S.O.L.I.D principles? ’. I quickly glanced at my code & assed the effort needed to introduce a new state. It would require the introduction of a new class with an additional switch-case block.

State-related logic is hard-coded in the VendingMachine class which means the Single-Responsibility principle is violated. Besides, a new feature requires me to modify the same class thus going against the Open-Closed principle.

I pondered over it for a while & eventually the thought of using State Design Pattern crossed my mind.

State Design Pattern

Following is a UML representation of the State design pattern:-

UML Diagram of State Design Pattern

For the Vending Machine design, we can declare a state interface which exposes the APIs — collectCash, dispenseChange, dispenseItem, cancelTransaction

All the states that we identified will implement the state interface. The Vending Machine becomes a context and stores a reference to the state.

Vending Machine class will delegate all the actions that it receives to the specific state classes. The individual states will process the command and perform a state transition by resetting the state in the context. Let’s have look at my modified code.

DispenseChange
DispenseItem
Ready
TransactionCancelled

With the above code, a new state can be easily defined and plugged into the existing implementation with minimal change. Further, individual states are decoupled from each other. Finally, I had a vending machine codebase which was reusable, extensible, readable & clean.

Mission Accomplished

Advantages

  • State-related behaviour is declared in an interface. New states can be easily introduced without the need to modify & add conditional blocks of code. Code becomes open for extension & closed for modification

Disadvantages

  • The pattern becomes an overkill if the design only has one or two states or the state behaviour rarely changes

Note:- You might find the State design pattern similar to the Strategy design pattern which was discussed in my last post here. The only difference is that in Strategy, the concrete strategy classes are not aware of each other whereas, in State pattern, the current state should be aware of the next state.

References:-

The Startup

Get smarter at building your thing. Join The Startup’s +788K followers.

Sign up for Top 10 Stories

By The Startup

Get smarter at building your thing. Subscribe to receive The Startup's top 10 most read stories — delivered straight into your inbox, once a week. Take a look.

By signing up, you will create a Medium account if you don’t already have one. Review our Privacy Policy for more information about our privacy practices.

Check your inbox
Medium sent you an email at to complete your subscription.

Animesh Gaitonde

Written by

Senior Software Engineer @Microsoft. Writes about Distributed Systems, Programming Languages & Tech Interviews

The Startup

Get smarter at building your thing. Follow to join The Startup’s +8 million monthly readers & +788K followers.

Animesh Gaitonde

Written by

Senior Software Engineer @Microsoft. Writes about Distributed Systems, Programming Languages & Tech Interviews

The Startup

Get smarter at building your thing. Follow to join The Startup’s +8 million monthly readers & +788K followers.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store