Design A Vending Auto Inwards Coffee - Interview Question
How arrive at y'all blueprint a Vending Machine inwards Java? is 1 of the practiced Java interview questions by as well as large asked at Senior flat Java developer Interviews. In a typical coding interview, y'all volition endure given a occupation disceptation to railroad train a vending machine as well as within a express time, usually, 2 to 3 hours y'all demand to arrive at blueprint document, working code as well as unit of measurement examine inwards Java. One of the substitution advantages of such Java interviews is that y'all tin examine many essential skills or a candidate inwards 1 go. In companionship to consummate the design, coding, as well as unit of measurement testing of a Vending machine, a candidate needs to endure actually practiced inwards all iii departments. By the way, this sort of existent basis occupation is besides a practiced exercise to improve your object-oriented analysis as well as blueprint skills (see here), which is really of import if y'all desire to driblet dead a practiced application developer.
By designing a vending machine inwards Java or whatever other object-oriented language, y'all non alone acquire basics e.g. Encapsulation, Polymorphism or Inheritance precisely besides learns subtle details of how to usage an abstract flat as well as interface (see here) field solving a occupation or designing an application.
Usually, this sort of occupation besides gives y'all an chance to utilize Java blueprint patterns, every bit inwards this occupation nosotros volition endure using Factory method pattern for creating unlike types of Vending Machine. I have got talked close this inquiry when I shared xx software blueprint questions inwards Java (here), as well as afterwards that, I have a lot of feedback to render a solution for that question.
This two-part series of posts volition render a solution of Vending machine occupation inwards Java. By the way, this occupation tin endure solved inwards a unlike way, as well as y'all should endeavour to arrive at that earlier looking into the solution given here. This is besides an chance to revisit SOLID as well as OOPS blueprint principles (see here) as well as acquire create to usage them inwards your code. You'll uncovering many of them are applicable when y'all blueprint vending machine inwards Java.
The requirement disceptation is the most of import component of the problem. You demand to read occupation disceptation multiple times to acquire a high-level agreement of the occupation as well as what are y'all trying to solve. Usually, requirements are non really clear as well as y'all demand to brand a listing of your ain past times reading through occupation statement.
I similar dot based requirement because it's slow to track. Some of the requirement are besides implicit precisely it's amend to acquire inwards explicit inwards your listing e.g. In this problem, vending machine should non bring a asking if it doesn't have got sufficient alter to return.
Unfortunately, at that topographic point is non many mass or course of written report which learn y'all these skills, y'all demand to railroad train them past times yourself past times doing roughly existent basis work. Though, 2 of the mass which helped me to improve past times object-oriented analysis as well as blueprint skills are Head First Object Oriented Design as well as Analysis 1st edition past times Brett D. McLaughlin. One of the best mass if y'all don't have got much sense inwards object oriented programming.
Another mass which is really practiced on developing application as well as organisation blueprint science is UML for Java Programmers past times Robert C. Martin, 1 of my favorite author. I have got read several books of him e.g. Clean Code, Clean Coder as well as a mass on software evolution using Agile. He is 1 of the best inwards educational activity OOP concept.
VendingMachine
It defines Earth API of vending machine, normally all high-level functionality should driblet dead inwards this class
VendingMachineImpl
Sample implementation of Vending Machine
VendingMachineFactory
Influenza A virus subtype H5N1 Factory flat to create unlike kinds of Vending Machine
Item
Java Enum to correspond Item served past times Vending Machine
Inventory
Java flat to correspond an Inventory, used for creating illustration as well as item inventory within Vending Machine
Coin
Another Java Enum to correspond Coins supported past times Vending Machine
Bucket
Influenza A virus subtype H5N1 parameterized flat to concur 2 objects. It's sort of Pair class.
NotFullPaidException
An Exception thrown past times Vending Machine when a user tries to collect an item, without paying the total amount.
NotSufficientChangeException
Vending Machine throws this exception to bespeak that it doesn't have got sufficient alter to consummate this request.
SoldOutExcepiton
Vending Machine throws this exception if the user asking for a production which is sold out.
VendingMachine.java
The public API of vending machine, normally all high-level functionality should driblet dead inwards this class
VendingMachineImpl.java
Influenza A virus subtype H5N1 sample implementation of VendingMachine interface represents a existent basis Vending Machine , which y'all run into inwards your office, motorcoach stand, railway station as well as world places.
VendingMachineFactory.java
Influenza A virus subtype H5N1 Factory flat to create unlike kinds of Vending Machine
Item.java
Java Enum to correspond Item served past times Vending Machine
Coin.java
Another Java Enum to correspond Coins supported past times Vending Machine
Inventory.java
Influenza A virus subtype H5N1 Java flat to correspond an Inventory, used for creating illustration as well as item inventory within Vending Machine.
Bucket.java
Influenza A virus subtype H5N1 parameterized utility flat to concur 2 objects.
NotFullPaidException.java
An Exception, thrown past times Vending Machine when a user tries to collect an item, without paying the total amount.
NotSufficientChangeException.java
Vending Machine throws this exception to bespeak that it doesn't have got sufficient alter to consummate this request.
SoldOutException.java
The Vending Machine throws this exception if the user asking for a production which is sold out
That's all inwards this start component of how to blueprint a vending machine inwards Java. In this part, nosotros have got solved the occupation past times creating all the classes as well as writing all code, precisely unit of measurement examine as well as blueprint document are notwithstanding pending, which y'all volition run into inwards the second part of this article.
If y'all desire y'all tin endeavour to run this occupation past times creating the Unit test, or possibly acquire inwards an application past times using a thread as well as thus usage a unlike thread to human activity every bit the user. You tin besides read UML for Java Programmers past times Robert C. Martin inwards the meantime.
Further Learning
Design Pattern Library
From 0 to 1: Design Patterns - 24 That Matter - In Java
Java Design Patterns - The Complete Masterclass
By designing a vending machine inwards Java or whatever other object-oriented language, y'all non alone acquire basics e.g. Encapsulation, Polymorphism or Inheritance precisely besides learns subtle details of how to usage an abstract flat as well as interface (see here) field solving a occupation or designing an application.
Usually, this sort of occupation besides gives y'all an chance to utilize Java blueprint patterns, every bit inwards this occupation nosotros volition endure using Factory method pattern for creating unlike types of Vending Machine. I have got talked close this inquiry when I shared xx software blueprint questions inwards Java (here), as well as afterwards that, I have a lot of feedback to render a solution for that question.
This two-part series of posts volition render a solution of Vending machine occupation inwards Java. By the way, this occupation tin endure solved inwards a unlike way, as well as y'all should endeavour to arrive at that earlier looking into the solution given here. This is besides an chance to revisit SOLID as well as OOPS blueprint principles (see here) as well as acquire create to usage them inwards your code. You'll uncovering many of them are applicable when y'all blueprint vending machine inwards Java.
Problem Statement
You demand to blueprint a Vending Machine which- Accepts coins of 1,5,10,25 Cents i.e. penny, nickel, dime, as well as quarter.
- Allow user to choose products Coke(25), Pepsi(35), Soda(45)
- Allow user to bring refund past times canceling the request.
- Return selected production as well as remaining alter if any
- Allow reset functioning for vending machine supplier.
The requirement disceptation is the most of import component of the problem. You demand to read occupation disceptation multiple times to acquire a high-level agreement of the occupation as well as what are y'all trying to solve. Usually, requirements are non really clear as well as y'all demand to brand a listing of your ain past times reading through occupation statement.
I similar dot based requirement because it's slow to track. Some of the requirement are besides implicit precisely it's amend to acquire inwards explicit inwards your listing e.g. In this problem, vending machine should non bring a asking if it doesn't have got sufficient alter to return.
Unfortunately, at that topographic point is non many mass or course of written report which learn y'all these skills, y'all demand to railroad train them past times yourself past times doing roughly existent basis work. Though, 2 of the mass which helped me to improve past times object-oriented analysis as well as blueprint skills are Head First Object Oriented Design as well as Analysis 1st edition past times Brett D. McLaughlin. One of the best mass if y'all don't have got much sense inwards object oriented programming.
Another mass which is really practiced on developing application as well as organisation blueprint science is UML for Java Programmers past times Robert C. Martin, 1 of my favorite author. I have got read several books of him e.g. Clean Code, Clean Coder as well as a mass on software evolution using Agile. He is 1 of the best inwards educational activity OOP concept.
This mass has got a similar occupation close designing a java machine. So, if y'all desire to exercise to a greater extent than or endeavour your object oriented blueprint skill, y'all tin refer to that problem. It's besides a really practiced learning exercise.
Solution as well as Coding
My implementation of Java Vending Machine has next classes as well as interfaces :VendingMachine
It defines Earth API of vending machine, normally all high-level functionality should driblet dead inwards this class
VendingMachineImpl
Sample implementation of Vending Machine
VendingMachineFactory
Influenza A virus subtype H5N1 Factory flat to create unlike kinds of Vending Machine
Item
Java Enum to correspond Item served past times Vending Machine
Inventory
Java flat to correspond an Inventory, used for creating illustration as well as item inventory within Vending Machine
Coin
Another Java Enum to correspond Coins supported past times Vending Machine
Bucket
Influenza A virus subtype H5N1 parameterized flat to concur 2 objects. It's sort of Pair class.
NotFullPaidException
An Exception thrown past times Vending Machine when a user tries to collect an item, without paying the total amount.
NotSufficientChangeException
Vending Machine throws this exception to bespeak that it doesn't have got sufficient alter to consummate this request.
SoldOutExcepiton
Vending Machine throws this exception if the user asking for a production which is sold out.
How to blueprint Vending Machine inwards Java
Here is the consummate code of Vending Machine inwards Java, brand certain to examine this code, as well as permit me know if y'all human face upwards whatever issue.VendingMachine.java
The public API of vending machine, normally all high-level functionality should driblet dead inwards this class
package vending; import java.util.List; /** * Decleare world API for Vending Machine * @author Javin Paul */ 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
Influenza A virus subtype H5N1 sample implementation of VendingMachine interface represents a existent basis Vending Machine , which y'all run into inwards your office, motorcoach stand, railway station as well as world places.
package vending; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * Sample implementation of Vending Machine inwards Java * @author Javin Paul */ 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 alongside v coins of each denomination //and v cans of each Item for(Coin c : Coin.values()){ cashInventory.put(c, 5); } for(Item i : Item.values()){ itemInventory.put(i, 5); } } @Override public long selectItemAndGetPrice(Item item) { if(itemInventory.hasItem(item)){ currentItem = item; return currentItem.getPrice(); } throw new SoldOutException("Sold Out, Please purchase roughly other item"); } @Override public void insertCoin(Coin coin) { currentBalance = currentBalance + coin.getDenomination(); cashInventory.add(coin); } @Override public Bucket<Item, List<Coin>> collectItemAndChange() { Item item = collectItem(); totalSales = totalSales + currentItem.getPrice(); List<Coin> change = collectChange(); return new Bucket<Item, List<Coin>>(item, change); } private Item collectItem() throws NotSufficientChangeException, NotFullPaidException{ if(isFullPaid()){ if(hasSufficientChange()){ itemInventory.deduct(currentItem); return currentItem; } throw new NotSufficientChangeException("Not Sufficient alter inwards Inventory"); } long remainingBalance = currentItem.getPrice() - currentBalance; throw new NotFullPaidException("Price non total paid, remaining : ", remainingBalance); } private List<Coin> collectChange() { long changeAmount = currentBalance - currentItem.getPrice(); List<Coin> change = getChange(changeAmount); updateCashInventory(change); currentBalance = 0; currentItem = null; return change; } @Override public List<Coin> refund(){ List<Coin> refund = getChange(currentBalance); updateCashInventory(refund); currentBalance = 0; currentItem = null; return refund; } private boolean isFullPaid() { if(currentBalance >= currentItem.getPrice()){ return true; } return false; } private List<Coin> getChange(long amount) throws NotSufficientChangeException{
List<Coin> changes = Collections.EMPTY_LIST; if(amount > 0){ changes = new ArrayList<Coin>(); long residuum = amount; while(balance > 0){ if(balance >= Coin.QUARTER.getDenomination() && cashInventory.hasItem(Coin.QUARTER)){ changes.add(Coin.QUARTER); residuum = residuum - Coin.QUARTER.getDenomination(); continue; }else if(balance >= Coin.DIME.getDenomination() && cashInventory.hasItem(Coin.DIME)) { changes.add(Coin.DIME); residuum = residuum - Coin.DIME.getDenomination(); continue; }else if(balance >= Coin.NICKLE.getDenomination() && cashInventory.hasItem(Coin.NICKLE)) { changes.add(Coin.NICKLE); residuum = residuum - Coin.NICKLE.getDenomination(); continue; }else if(balance >= Coin.PENNY.getDenomination() && cashInventory.hasItem(Coin.PENNY)) { changes.add(Coin.PENNY); residuum = residuum - Coin.PENNY.getDenomination(); continue; }else{ throw new NotSufficientChangeException("NotSufficientChange, Please endeavour roughly other product"); } } } return changes; } @Override public void reset(){ cashInventory.clear(); itemInventory.clear(); totalSales = 0; currentItem = null; currentBalance = 0; } public void printStats(){ System.out.println("Total Sales : " + totalSales); System.out.println("Current Item Inventory : " + itemInventory); System.out.println("Current Cash Inventory : " + cashInventory); } private boolean hasSufficientChange(){ return hasSufficientChangeForAmount(currentBalance - currentItem.getPrice()); } private boolean hasSufficientChangeForAmount(long amount){ boolean hasChange = true; try{ getChange(amount); }catch(NotSufficientChangeException nsce){ return hasChange = false; } return hasChange; } private void updateCashInventory(List change) { for(Coin c : change){ cashInventory.deduct(c); } } public long getTotalSales(){ return totalSales; } }
VendingMachineFactory.java
Influenza A virus subtype H5N1 Factory flat to create unlike kinds of Vending Machine
package vending; /** * Factory flat to create instance of Vending Machine, this tin endure extended to create instance of * unlike types of vending machines. * @author Javin Paul */ public class VendingMachineFactory { public static VendingMachine createVendingMachine() { return new VendingMachineImpl(); } }
Item.java
Java Enum to correspond Item served past times Vending Machine
package vending; /** * Items or products supported past times Vending Machine. * @author Javin Paul */ public enum Item{ COKE("Coke", 25), PEPSI("Pepsi", 35), SODA("Soda", 45); private String name; private int price; private Item(String name, int price){ this.name = name; this.price = price; } public String getName(){ return name; } public long getPrice(){ return price; } }
Coin.java
Another Java Enum to correspond Coins supported past times Vending Machine
package vending; /** * Coins supported past times Vending Machine. * @author Javin Paul */ public enum Coin { PENNY(1), NICKLE(5), DIME(10), QUARTER(25); private int denomination; private Coin(int denomination){ this.denomination = denomination; } public int getDenomination(){ return denomination; } }
Inventory.java
Influenza A virus subtype H5N1 Java flat to correspond an Inventory, used for creating illustration as well as item inventory within Vending Machine.
package vending; import java.util.HashMap; import java.util.Map; /** * An Adapter over Map to create Inventory to concur cash as well as * Items within Vending Machine * @author Javin Paul */ public class Inventory<T> { private Map<T, Integer> inventory = new HashMap<T, Integer>(); public int getQuantity(T item){ Integer value = inventory.get(item); return value == null? 0 : value ; } public void add(T item){ int count = inventory.get(item); inventory.put(item, count+1); } public void deduct(T item) { if (hasItem(item)) { int count = inventory.get(item); inventory.put(item, count - 1); } } public boolean hasItem(T item){ return getQuantity(item) > 0; } public void clear(){ inventory.clear(); } public void put(T item, int quantity) { inventory.put(item, quantity); } }
Bucket.java
Influenza A virus subtype H5N1 parameterized utility flat to concur 2 objects.
package vending; /** * Influenza A virus subtype H5N1 parameterized utility flat to concur 2 unlike object. * @author Javin Paul */ public class Bucket<E1, E2> { private E1 first; private E2 second; public Bucket(E1 first, E2 second){ this.first = first; this.second = second; } public E1 getFirst(){ return first; } public E2 getSecond(){ return second; } }
NotFullPaidException.java
An Exception, thrown past times Vending Machine when a user tries to collect an item, without paying the total amount.
package vending; public class NotFullPaidException extends RuntimeException { private String message; private long remaining; public NotFullPaidException(String message, long remaining) { this.message = message; this.remaining = remaining; } public long getRemaining(){ return remaining; } @Override public String getMessage(){ return message + remaining; } }
NotSufficientChangeException.java
Vending Machine throws this exception to bespeak that it doesn't have got sufficient alter to consummate this request.
package vending; public class NotSufficientChangeException extends RuntimeException { private String message; public NotSufficientChangeException(String string) { this.message = string; } @Override public String getMessage(){ return message; } }
SoldOutException.java
The Vending Machine throws this exception if the user asking for a production which is sold out
package vending; public class SoldOutException extends RuntimeException { private String message; public SoldOutException(String string) { this.message = string; } @Override public String getMessage(){ return message; } }
That's all inwards this start component of how to blueprint a vending machine inwards Java. In this part, nosotros have got solved the occupation past times creating all the classes as well as writing all code, precisely unit of measurement examine as well as blueprint document are notwithstanding pending, which y'all volition run into inwards the second part of this article.
If y'all desire y'all tin endeavour to run this occupation past times creating the Unit test, or possibly acquire inwards an application past times using a thread as well as thus usage a unlike thread to human activity every bit the user. You tin besides read UML for Java Programmers past times Robert C. Martin inwards the meantime.
Further Learning
Design Pattern Library
From 0 to 1: Design Patterns - 24 That Matter - In Java
Java Design Patterns - The Complete Masterclass
0 Response to "Design A Vending Auto Inwards Coffee - Interview Question"
Post a Comment