How to design a vending machine in Java?

How to design a vending machine in Java? is one of the good questions that are often asked in interviews for senior Java developers. In a typical coding interview, you are given a problem description to develop a vending machine, and within a limited time, usually 2 to 3 hours, you are required to write a design document, working code, and unit tests in Java. A key advantage of this type of Java interview is that it tests many basic skills of the candidate at once. In order to complete the design, coding and unit testing of the vending machine, the candidate needs to be excellent in all three areas.

By the way, this kind of real-world problem is also a good exercise to improve your object-oriented analysis and design skills, which is very important if you want to become a good application developer.

By designing vending machines in Java or any other object-oriented language, you not only learn the basics like encapsulation, polymorphism, or inheritance, but you also learn the subtle details of using abstract classes and interfaces when solving problems or designing applications.

Usually, this kind of problem also provides the opportunity to utilize Java design patterns. In this problem, we will use the Factory Method pattern to create different types of vending machines. I talked about this issue when I shared 20 Java Software Design Problems (here), and since then, I've received a lot of feedback offering solutions to this problem.

This two-part article will provide a solution to the vending machine problem in Java. By the way, this problem can be solved in different ways, you should try to do that before looking at the solutions given here. This is also an opportunity to brush up on the SOLID and OOPS design principles found here and prepare to use them in your code. You'll find many of these applicable when designing a vending machine in Java.

By the way, if you are serious about learning design patterns and principles, I recommend checking out the Java Design Patterns course on Udemy. The course covers SOLID design principles such as the open-closed principle and Liskov substitution, as well as all important object-oriented design patterns such as decorators, observers, chain of responsibility, and more.

problem statement

You need to design a vending machine that

  • Accepts 1, 5, 10 and 25 cent coins, i.e. pennies, nickels, dimes and quarters.

  • Allows users to select products: Coke (25 cents), Pepsi (35 cents), soda (45 cents)

  • Allow users to get refunds by canceling requests.

  • If there is any left, return the selected product and the remaining change

  • Allows vending machine vendors to reset operations.

The requirement statement is the most important part of the question. You need to read the problem statement multiple times to gain a high-level understanding of the problem and the problem you are trying to solve. Often, the requirements are not very clear and you need to develop your own list of requirements by reading the problem statement.

I like bullet-based requirements because it's easy to keep track of. Some requirements are also implicit, but it's better to make them explicit in your list, for example, in this question, if the vending machine doesn't have enough change to complete the transaction, it shouldn't accept the request.

Unfortunately, not many books or courses teach you these skills, you need to develop these skills yourself through some real work.

Although two resources that have helped me improve my object-oriented analysis and design skills are "In-Depth Object-Oriented Design Interviews" on Educative, an interactive course that allows you to practice object-oriented questions in your browser, which I highly recommend Take this course to improve your object-oriented design skills.

Java Software Design Issues - Vending Machine Solution

The second resource is Brett D. McLaughlin's "Introduction to Object-Oriented Design and Analysis," first edition. This is one of the best books to read if you don't have much experience with object-oriented programming.

Solutions and coding

My implementation of a Java vending machine has the following classes and interfaces:

  • VendingMachine
    defines the public API of the vending machine, usually all advanced functions should be in this class

  • VendingMachineImpl
    An example implementation of Vending Machine

  • VendingMachineFactory creates factory classes for different types of Vending Machines

  • Item
    represents a Java enumeration of the items provided by the Vending Machine

  • Inventory Java class representing inventory, used to create deposits and product inventory in Vending Machine

  • Coin Another Java enumeration representing the coins supported by the Vending Machine

  • Bucket A parameterized class to hold two objects. It's a bit like the Pair class.

  • NotFullPaidException Vending Machine throws this exception when a user attempts to collect an item without paying the full amount.

  • NotSufficientChangeException This exception is thrown by the Vending Machine to indicate that it does not have enough change to complete this request.

  • SoldOutExcepiton If the item requested by the user has been sold out, Vending Machine will throw this exception.

Below is the complete code for the vending machine in Java, please make sure to test this code and let me know if you encounter any issues.

// VendingMachine.java

public interface VendingMachine {
   
  public long selectItemAndGetPrice(Item item);
  
  public void insertCoin(Coin coin);
  
  public List<Coin> refund();

  public Bucket<Item, List<Coin>> collectItemAndChange();

  public void reset();

}

// VendingMachineImpl.java

public class VendingMachineImpl implements VendingMachine {

  private Inventory<Coin> cashInventory = new Inventory<Coin>();

  private Inventory<Item> itemInventory = new Inventory<Item>();

  private long totalSales;

  private Item currentItem;

  private long currentBalance;

  public VendingMachineImpl(){
    initialize();
  }

  private void initialize(){

    // initialize machine 
    for(Coin c : Coin.values()){
      cashInventory.put(c, 5); 
    }

    for(Item i : Item.values()){
      itemInventory.put(i, 5);
    }

  }

  // 其他方法

  public void printStats(){
    System.out.println("Total Sales : " + totalSales);
    System.out.println("Current Item Inventory : " + itemInventory);
    System.out.println("Current Cash Inventory : " + cashInventory);
  }

}

// 其他类定义

That’s it for the first part of this article on how to design a vending machine in Java. In this part, we solved the problem by creating all the classes and writing all the code, but the unit tests and design documentation are still pending, as you will see in the second part of this article.

If you wanted, you could run this problem by creating unit tests, or perhaps by using threads to make it an application, and then use another thread to act as the user.

If you need more object-oriented design questions to practice with, I recommend checking out the In-Depth Object-Oriented Design Interview course on Educative, an interactive learning platform. Designed by hiring managers at Google, Facebook, Microsoft, and Amazon, the course includes solutions to some of the most common object-oriented design questions asked by these tech giants. Original link

This article is published by OpenWrite, a blog that publishes multiple articles !

OpenAI opens ChatGPT to all users for free. Voice programmers tampered with ETC balances and embezzled more than 2.6 million yuan a year. Spring Boot 3.2.0 was officially released. Google employees criticized the big boss after leaving the company. He was deeply involved in the Flutter project and formulated HTML-related standards. Microsoft Copilot Web AI will be Officially launched on December 1st, supporting Chinese Microsoft's open source Terminal Chat Rust Web framework Rocket releases v0.5: supports asynchronous, SSE, WebSockets, etc. The father of Redis implements the Telegram Bot framework using pure C language code . If you are an open source project maintainer, encounter How far can you endure this kind of response? PHP 8.3 GA
{{o.name}}
{{m.name}}

Guess you like

Origin my.oschina.net/u/3494859/blog/10143522