Problem overview
A shop keeps its orders in a cart. You build two classes that work together. A LineItem is one row of the cart: a product name, a price and a quantity. A Cart holds many rows and adds them up.
LineItem has three public fields, string name, double price and int quantity, a constructor that stores them, and a method Subtotal() returning price * quantity. Cart keeps a private List<LineItem> items, adds rows with Add(LineItem item), and reports Total(), the sum of all subtotals.
In the driver, an apple at price 5 with quantity 3 has a subtotal of 15. A cart holding the apple and bread at price 20 with quantity 3 totals 75. After a milk row (price 10, quantity 2) is added, the same cart's next total is 95. An empty cart totals 0.
Approach: a cart has rows
The relationship is composition. A cart has line items; it is not one, so it doesn't inherit from LineItem. It simply holds them in a list.
The cart also doesn't know how a row computes its cost. It asks each row for Subtotal() and adds up the answers. If rows later priced themselves differently, Total() would not change.
The total is computed each time it is requested, not stored. That is why adding the milk row changes the next total without any extra bookkeeping.
Step by step
- Declare
LineItem. The driver'snew LineItem(...)builds objects from it. - Add the public field
name, astring. - Add
price, adouble, in case a price isn't a whole number. - Add
quantity, anint, because how many were bought is always whole. - Write the constructor. It is named
LineItem, like the class, and has no return type. It takesname,priceandquantity. - Store the name with
this.name = name;. The parameter and the field share a name, sothis.tells C# which one is the field. - Store the price the same way.
- Store the quantity the same way.
- Add
Subtotal, a public method returningdouble. - Return
price * quantity. Both are fields of this row, so nothis.is needed. - Declare
CartbelowLineItem. - Add the private field
items, aList<LineItem>starting as a new empty list. Rows arrive one at a time, and a list grows as you add. - Add the method
Add, public andvoid, taking aLineItemnameditem. - Call
items.Add(item). The list keeps rows in the order they came in. - Add
Total, a public method returningdouble. Its body takes three lines. - Start
double sum = 0;. A running total starts at zero, so an empty cart gives 0. - Loop with
foreachoveritemsand add each row'sSubtotal()tosum.foreachhands you each element in turn, so you need no index. - Return
sumonce, after the loop.
The solution in C#
class LineItem {
public string name;
public double price;
public int quantity;
public LineItem(string name, double price, int quantity) {
this.name = name;
this.price = price;
this.quantity = quantity;
}
public double Subtotal() {
return price * quantity;
}
}
class Cart {
private List<LineItem> items = new List<LineItem>();
public void Add(LineItem item) {
items.Add(item);
}
public double Total() {
double sum = 0;
foreach (var item in items) sum += item.Subtotal();
return sum;
}
}
class Solution {
public void MainFunction() {
Cart empty = new Cart();
Console.WriteLine("Empty: " + empty.Total());
LineItem apple = new LineItem("Apple", 5, 3);
Console.WriteLine("Subtotal: " + apple.Subtotal());
Cart cart = new Cart();
cart.Add(apple);
cart.Add(new LineItem("Bread", 20, 3));
Console.WriteLine("Total: " + cart.Total());
cart.Add(new LineItem("Milk", 10, 2));
Console.WriteLine("Total: " + cart.Total());
}
}
The driver prints:
Empty: 0
Subtotal: 15
Total: 75
Total: 95
C# details
- Constructor and methods. The constructor
LineItemhas no return type.Cart.Addis an ordinary method that shares its name withList.Add, but inside ititems.Add(item)is a call on the list, so it does not call itself. varinforeach.foreach (var item in items)lets the compiler infer thatitemis aLineItem. WritingLineItem itemwould mean the same.- Mixed arithmetic.
price * quantitymultiplies adoubleby anint; the int is converted, and the result is adouble. - Printing doubles. A
doubleholding 75 prints as75, which is why the output has no decimal point. - Rows are shared objects.
LineItemis a class, so the cart stores a reference to the same object the caller has. If the caller setsapple.quantity = 10after adding it, the cart's next total counts 10 apples. In the driver's cart that turns the total of 95 into 130.
Complexity
Add is O(1) on average. Total visits every row once, so it takes O(n) time for n rows and O(1) extra space. The cart itself uses O(n) space for its rows.
Edge cases and common mistakes
- Empty cart. The loop never runs and
sumstays 0. - Storing the total. Keeping a total field and updating it in
Addworks until a row changes. Computing it inTotal()always matches the current rows. - Declaring
suminside the loop. It would restart at 0 for every row, and the return would not compile becausesumwould be out of scope. - Forgetting
this.in the constructor.name = name;assigns the parameter to itself and leaves the field empty. The compiler only warns about it. - Decimal prices. They work, but doubles are approximate: a price of 0.1 with quantity 3 gives
0.30000000000000004. A price of 2.5 with quantity 3 gives7.5. The lesson's driver uses whole numbers.
Testing
- A cart holding only the apple (5 times 3) gives a total of
15. - The same row added twice to one cart counts twice. With the apple at quantity 10 added twice the total is
100. - A row of price 2.5 and quantity 3 has a subtotal of
7.5.
