cppadvanced20 minutes

Advanced C++ Code Refactor: Optimize and Modernize Complex Class Implementation

Given a legacy C++ class with complex logic, repetitive code, and poor maintainability, your task is to refactor it for readability, efficiency, and modern C++ best practices without altering its external behavior.

Challenge prompt

You are provided with a complex C++ class that performs multiple operations with several duplicated code blocks, manual memory management, and non-idiomatic constructs. Refactor the class using modern C++ features such as smart pointers, STL algorithms, and remove code duplication. Improve the class design for readability and maintainability, but ensure the external interface and behavior remain unchanged. Provide only the refactored class implementation.

Guidance

  • Focus on eliminating duplicated code by introducing helper functions or templates where appropriate.
  • Replace raw pointers and manual memory management with smart pointers to ensure exception safety.
  • Leverage STL algorithms and range-based loops to simplify iterations and conditional logic.
  • Maintain the original class interface and ensure all unit tests (if any) still pass after your refactor.

Hints

  • Consider using std::unique_ptr or std::shared_ptr instead of raw pointers for resource management.
  • Use std::transform, std::accumulate, or std::any_of to replace manual loops where appropriate.
  • Look out for patterns of repeated code blocks that can be abstracted into smaller functions.

Starter code

class DataProcessor {
  int* data;
  size_t size;

public:
  DataProcessor(size_t n) : size(n) {
    data = new int[size];
    for (size_t i = 0; i < size; ++i) {
      data[i] = i * 2;
    }
  }

  ~DataProcessor() {
    delete[] data;
  }

  void process() {
    for (size_t i = 0; i < size; ++i) {
      if (data[i] % 2 == 0) {
        data[i] = data[i] / 2;
      } else {
        data[i] = data[i] * 3;
      }
    }
  }

  int sum() const {
    int total = 0;
    for (size_t i = 0; i < size; ++i) {
      total += data[i];
    }
    return total;
  }

  bool contains(int val) const {
    for (size_t i = 0; i < size; ++i) {
      if (data[i] == val) {
        return true;
      }
    }
    return false;
  }
};

Expected output

Class behavior remains unchanged: for example, DataProcessor dp(5); dp.process(); std::cout << dp.sum(); // Outputs 12 std::cout << dp.contains(3); // Outputs 1 (true) std::cout << dp.contains(10); // Outputs 0 (false)

Core concepts

Modern C++Smart pointersSTL algorithmsCode refactoring

Challenge a Friend

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