cppintermediate10 minutes

Refactor Messy Inventory Management Code

Improve the structure and readability of a cluttered C++ function that manages inventory updates while preserving its original behavior.

Challenge prompt

You are given a function that updates the stock quantities of items in an inventory based on incoming orders. The current implementation is messy, with nested conditionals, duplicated code, and unclear variable names. Refactor the code to improve its readability, maintainability, and remove duplication without changing its behavior. Ensure the function still correctly updates the inventory and handles orders as expected.

Guidance

  • Focus on simplifying nested if-else statements and reducing code duplication.
  • Use meaningful variable names to enhance code clarity.
  • Consider breaking down the function into smaller helper functions if helpful.

Hints

  • Identify and extract repeated code blocks into separate functions or loops.
  • Use standard library features such as range-based for loops and references to clean up iteration.

Starter code

void updateInventory(std::map<std::string, int> &inventory, const std::vector<std::pair<std::string, int>> &orders) {
    for (size_t i = 0; i < orders.size(); i++) {
        std::string item = orders[i].first;
        int qty = orders[i].second;
        if (inventory.find(item) != inventory.end()) {
            if (qty > 0) {
                int currentStock = inventory[item];
                if (currentStock >= qty) {
                    inventory[item] = currentStock - qty;
                } else {
                    inventory[item] = 0;
                }
            } else {
                if (qty < 0) {
                    inventory[item] = inventory[item] + (-qty);
                } // else do nothing for zero qty
            }
        } else {
            if (qty < 0) {
                inventory[item] = -qty;
            } else {
                // do nothing if positive qty but item not found
            }
        }
    }
}

Expected output

After refactoring, the function behaves identically to the original implementation, correctly updating inventory quantities based on the orders vector.

Core concepts

code refactoringstd::maploopsconditional logic

Challenge a Friend

Send this duel to someone else and see if they can solve it.