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 delivered. The class InventoryItem therefore 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 and returnstrueifnis at least 1 and at most the stock. Otherwise it changes nothing and returnsfalse.Restock(n)addsnpieces whennis at least 1, and ignores it otherwise.GetStock()returns the stock.
For 5 pencils, Sell(3) works and leaves 2. Sell(5) is refused because only 2 are left. Restock(10) then brings the stock to 12.
Approach
The key idea is to refuse bad requests before anything changes. In Sell, first test whether the request is invalid: n below 1 (zero or negative pieces make no sense) or above the stock (the shop doesn't have that many). If so, return false and leave the stock alone. Only a request that passes gets to the line that lowers the stock, so the stock can't become negative.
Because the check comes first, the method needs no undo step, and every call is O(1). Selling exactly the whole stock is allowed: n equal to the stock passes the check and leaves 0.
Step by step
- Declare
public string name. Other code may read the name directly. - Declare
private int stock. Only code inside the class can use it; outside,item.stockis a compile error. - Constructor: store both parameters with
this.nameandthis.stock. The parameters share the fields' names, sothis.picks the fields. - In
Sell, write anifforn < 1 || n > stockjoined with||. Its body returnsfalse. - After the
if, lower the stock bynand returntrue. - In
Restock, addnto the stock only ifn >= 1. Zero or a negative number isn't a delivery. GetStockreturns the stock. It is the only way for other code to read it.
The solution in C#
class InventoryItem {
public string name;
private int stock;
public InventoryItem(string name, int stock) {
this.name = name;
this.stock = stock;
}
public bool 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;
}
}
Using it:
var p = new InventoryItem("Pencil", 5);
Console.WriteLine(p.Sell(3));
Console.WriteLine(p.GetStock());
Console.WriteLine(p.Sell(5));
Console.WriteLine(p.GetStock());
p.Restock(10);
Console.WriteLine(p.GetStock());
This prints:
True
2
False
2
12
C# writes a bool as True or False when it is printed, and the lesson's tests print the answers the same way.
Details worth knowing
- Public and private together.
nameis public, sop.namegives"Pencil".p.stockdoes not compile, because the field is private. - The
||operator. It stops as soon as the left side is true. For a request of -3, the first test already decides, and the second test is not evaluated. - Return values carry the outcome.
Sellreturns aboolso callers know whether the sale happened.Restockreturns nothing: ignoring a bad delivery is silent by design. - Refused calls change nothing. After a failed
Sell,GetStock()returns what it did before the call.
Edge cases and common mistakes
- Selling everything. A
Sellof the full stock returnstrueand leaves 0. Writingn >= stockas the refusal would wrongly refuse it. With a stock of 4 mugs,Sell(4)givesTrueand stock 0, and the nextSell(1)givesFalse. - Zero and negative amounts. For a lamp with stock 2,
Sell(0)andSell(-3)returnFalse, andRestock(0)andRestock(-5)change nothing, so the stock is still 2. A negative sale would otherwise increase the stock, and a negative restock would decrease it. - Changing before checking. Lowering the stock first and testing afterwards leaves a negative stock behind when the test fails.
- Using
&&instead of||. A request is invalid if either condition holds; no number is both below 1 and above the stock. - Restock then sell. After
Restock(1)on the lamp there are 3, andSell(3)returnsTrueand leaves 0.
Testing
- Pencil with 5:
Sell(3)True, stock 2,Sell(5)False, stock 2,Restock(10), stock 12. - Mug with 4:
Sell(4)True, stock 0,Sell(1)False, stock 0. - Lamp with 2:
Sell(0)andSell(-3)False;Restock(0)andRestock(-5)ignored; stock 2;Restock(1);Sell(3)True; stock 0.
Why private fields need methods
Making stock private is only half of the design. The other half is that the class offers exactly the operations a shop needs, each with its rule. Code outside can ask to sell, ask to restock and ask for the number, but it can never set the stock to -7 or to a number that doesn't match what really happened.
Compare the alternative, a public stock field. Every place that sells something would repeat the test n <= stock, and a single place that forgets it can put the item in an invalid state. With the private field, the rules live in two short methods, and they are the only places to read when something looks wrong.
The name is public because nothing can go wrong with it: any value is a valid name. Choosing what to protect, and leaving the rest simple, is part of the design.
Key takeaways
- Check the request first, change the state second.
- Return a
boolwhen the caller needs to know whether an operation happened. - Protect fields that have rules, and leave harmless ones public.
