Refactor Legacy Inventory Management Code for Efficiency and Readability
Improve an inefficient, hard-to-read inventory management function written in C++ by refactoring it to use modern C++ features, enhance performance, and maintain identical behavior.
Challenge prompt
You are given a legacy function that manages inventory updates in a warehouse system. The function is overly complex, uses inefficient looping, and is hard to maintain. Refactor the function to improve its readability, reduce complexity, optimize performance where possible, and utilize modern C++ best practices, including standard library algorithms and proper use of const correctness. Your refactored function should produce the exact same output and side effects as the original.
Guidance
- • Preserve the original function’s behavior and output after refactoring.
- • Focus on simplifying nested loops and conditionals without changing logic.
- • Leverage C++ STL containers and algorithms to replace manual iterations.
- • Improve variable naming and code structure for better maintainability.
Hints
- • Consider using std::unordered_map or std::map to optimize lookup operations.
- • Use range-based for loops and const references to avoid unnecessary copies.
- • Extract smaller helper functions if certain blocks perform distinct subtasks.
Starter code
#include <iostream>
#include <vector>
#include <string>
struct Item {
std::string name;
int quantity;
};
// Legacy function: updates inventory quantities based on shipments and removals
void updateInventory(std::vector<Item>& inventory,
const std::vector<Item>& shipments,
const std::vector<Item>& removals) {
// Increase quantities for shipments
for (size_t i = 0; i < shipments.size(); ++i) {
bool found = false;
for (size_t j = 0; j < inventory.size(); ++j) {
if (inventory[j].name == shipments[i].name) {
inventory[j].quantity = inventory[j].quantity + shipments[i].quantity;
found = true;
}
}
if (!found) {
Item newItem;
newItem.name = shipments[i].name;
newItem.quantity = shipments[i].quantity;
inventory.push_back(newItem);
}
}
// Decrease quantities for removals
for (size_t i = 0; i < removals.size(); ++i) {
for (size_t j = 0; j < inventory.size(); ++j) {
if (inventory[j].name == removals[i].name) {
inventory[j].quantity = inventory[j].quantity - removals[i].quantity;
if (inventory[j].quantity < 0) {
inventory[j].quantity = 0;
}
}
}
}
}
int main() {
std::vector<Item> inventory = { {"apple", 10}, {"banana", 5} };
std::vector<Item> shipments = { {"orange", 7}, {"apple", 3} };
std::vector<Item> removals = { {"banana", 2}, {"apple", 15} };
updateInventory(inventory, shipments, removals);
for (const auto& item : inventory) {
std::cout << item.name << ": " << item.quantity << std::endl;
}
return 0;
}
Expected output
apple: 0 banana: 3 orange: 7
Core concepts
Challenge a Friend
Send this duel to someone else and see if they can solve it.