Start learning free

LESSON 164 OF 173 · BACKEND: BACKEND WITH AI

A Shared Default

Practice

The shop keeps each customer's cart in the dictionary carts, and its routes make new carts with MakeCart: {"owner": "ana", "items": []}. The items parameter lets the PUT route bring back a saved cart; without it, a cart starts empty. C# doesn't accept = new List<string>() as a default value (a default must be a constant), so an AI assistant made one empty list next to carts and used it whenever no list came in:

var noItems = new List<string>();

Dictionary<string, object> MakeCart(string owner, List<string> items = null) {
    return new Dictionary<string, object> { ["owner"] = owner, ["items"] = items ?? noItems };
}

Then Ben added a pen and found Ana's mug in his cart. The line that makes noItems runs once, when the app starts, not at each call. So every cart made without items gets that same one list, and what one customer adds, every customer sees. This is a shared default. A smaller example:

var tagList = new List<string>();

List<string> AddTag(string tag, List<string> tags = null) {
    tags = tags ?? tagList;
    tags.Add(tag);
    return tags;
}

Console.WriteLine(string.Join(", ", AddTag("new")));    // new
Console.WriteLine(string.Join(", ", AddTag("sale")));   // new, sale: the same list again

The fix: use null as the default. null can't be changed, so sharing it is harmless. Then, inside the function, make a new empty list when the value is null: lines inside a function run at every call, so every call gets a list of its own. A list that was passed in, like a restored cart, is kept as it is.

Your rewrite must give these answers:

POST /carts/ana/items  {"product": "Mug"}   →  201  {"owner": "ana", "items": ["Mug"]}
POST /carts/ben/items  {"product": "Pen"}   →  201  {"owner": "ben", "items": ["Pen"]}
POST /carts/ana/items  {"product": "Lamp"}  →  201  {"owner": "ana", "items": ["Mug", "Lamp"]}
GET  /carts/ben                             →  200  {"owner": "ben", "items": ["Pen"]}
GET  /carts/eva                             →  200  {"owner": "eva", "items": []}
PUT  /carts/chloe  {"items": ["Plant", "Teapot"]}  →  200  {"owner": "chloe", "items": ["Plant", "Teapot"]}

Your task: write MakeCart so a cart made without items gets a new empty list of its own, and a cart made with items keeps that list.


Assignment
Follow the Coding Tutorial to write MakeCart with null as the default and a new list made inside the function.


Hint
The new list must be made inside the function, so it runs at every call. Check with items == null. When AI code makes one list or dictionary and hands it to every caller, ask whether they all share it.


STEP 1 OF 4
    Ctrl + Enter to check