Problem overview
A shop tracks how many pieces of each item it has. The stock can never go below 0, and it changes only when pieces are sold or new ones arrive. So InventoryItem keeps the stock in a private field and changes it only through two methods that check the rules. The item's name has no rules to protect, so it is a public field.
InventoryItem(name, stock)creates an item with that name and that many pieces.sell(n)sellsnpieces ifnis at least 1 and at most the stock, lowering the stock and returningtrue. Otherwise it changes nothing and returnsfalse.restock(n)addsnpieces whennis at least 1 and ignoresnotherwise. It returns nothing.getStock()returns the stock, the only way for other code to read it.
For an item with a stock of 5, sell(3) returns true and leaves 2. Then sell(5) returns false because only 2 are left, and the stock stays 2. restock(10) brings it to 12.
Approach: check first, then change
Both methods follow the same pattern. First look at the request, and refuse it if it breaks a rule. Only then change the stock. For sell, a request is refused when n is below 1 (zero or negative pieces are not a sale) or above the stock (you can't sell what you don't have). Selling exactly the whole stock is fine and leaves 0. Because the check comes before any change, a refused sale leaves the stock as it was, and no code path can push the stock below 0.
Making stock private is what gives these checks their force. Outside the class, the only way to change the stock is through sell and restock, so every change is checked.
Step by step
- Declare
public String name. Other code may read it directly. - Declare
private int stock. Outside the class,item.stockis a compile error. - Store both parameters in the fields with
this.nameandthis.stock. - In
sell, refuse bad requests first:if (n < 1 || n > stock)returnsfalse. The two conditions are joined with||, "or". - Complete the sale: after the
if, subtractnfromstockand returntrue. Only a request that passed the check reaches this line. - In
restock, add only for a real delivery: ifn >= 1, addntostock. Zero or a negative number is ignored. getStockreturnsstock.
The solution in Java
class InventoryItem {
public String name;
private int stock;
public InventoryItem(String name, int stock) {
this.name = name;
this.stock = stock;
}
public boolean sell(int n) {
if (n < 1 || n > stock) {
return false;
}
stock -= n;
return true;
}
public void restock(int n) {
if (n >= 1) {
stock += n;
}
}
public int getStock() {
return stock;
}
}
Details worth noting:
- Inside
sell,stockis the field andnis the parameter. There is no name clash, sothis.isn't needed there. - The method returns early with
return false, so the lines below theifrun only for a valid sale. - The return type of
restockisvoid: it reports nothing, even when it ignores the request. - In the tests,
sell's answer is printed asTrueorFalse. That is the tests' output format; Java printstrueandfalse.
Using the class
InventoryItem it = new InventoryItem("Pencil", 5);
System.out.println(it.sell(3));
System.out.println(it.getStock());
System.out.println(it.sell(5));
System.out.println(it.getStock());
it.restock(10);
System.out.println(it.getStock());
System.out.println(it.name);
InventoryItem l = new InventoryItem("Lamp", 2);
System.out.println(l.sell(0) + " " + l.sell(-3));
l.restock(0);
l.restock(-5);
System.out.println(l.getStock());
l.restock(1);
System.out.println(l.sell(3) + " " + l.getStock());
prints:
true
2
false
2
12
Pencil
false false
2
true 0
The lamp case shows every rule: selling 0 or -3 is refused, restocking 0 or -5 is ignored, so the stock is still 2. After restock(1) there are 3 lamps, and selling all 3 works and leaves 0.
What the compiler does with private
From another class, item.stock is rejected at compile time with error: stock has private access in InventoryItem, whether you try to read it or to assign it. Reading goes through getStock(), and the only ways to change the number are sell and restock. The name is different: item.name is public, so other code can read it, and also change it, because no rule protects it.
Each item has its own stock. Selling pencils from one InventoryItem never changes the stock of another object, even one with the same name.
Edge cases and common mistakes
- Selling exactly the stock. Use
n > stockfor the refusal, notn >= stock, or the shop could never sell its last pieces. - Forgetting the lower bound. Without
n < 1,sell(-3)would pass the check and raise the stock by 3 while returningtrue. - Using
&&where||belongs. No number is both below 1 and above the stock, so that condition would never refuse anything. - Changing the stock before checking. The check must come first, or a refused sale would still modify the stock.
- Making
stockpublic. Code outside could then writeitem.stock = -5and break the rule the class exists to protect. - Accepting a negative restock.
restock(-5)would quietly act as a sale without any of its checks.
Complexity
Each method does a couple of comparisons and at most one arithmetic update, so all four are O(1) in time. The object stores a name and one integer.
