Refactor a Complex C++ Class for Cleaner Design and Performance
Refactor the given C++ class that manages a large dataset with inefficient and messy logic. Improve code readability, maintainability, and performance while preserving functionality.
Challenge prompt
You are given a C++ class 'DataProcessor' that processes a vector of integers. The current implementation has poor naming, redundant computations, and lacks proper encapsulation and const-correctness. Refactor the class to improve code quality without changing its external behavior or output. Your tasks: - Rename variables and methods for clarity. - Remove redundant or repeated computations. - Apply const correctness where applicable. - Encapsulate data members properly. - Simplify complex or nested logic. Ensure the public interface remains unchanged. Add comments if needed for complex logic. Do not modify the main function provided for testing; only refactor the class definition and implementation.
Guidance
- • Focus on improving variable and method names for self-documenting code.
- • Identify repeated calculations and move them outside loops if possible.
- • Use const on member functions that do not modify class state.
- • Make private data members truly private and provide accessors if needed.
Hints
- • Look for loops that recalculate the same values repeatedly and cache them.
- • Consider the use of const references to avoid unnecessary copies.
- • Avoid using public data members; use private members with public getter methods.
Starter code
class DataProcessor {
public:
std::vector<int> data;
int processData() {
int result = 0;
for (int i = 0; i < data.size(); ++i) {
int val = data[i];
for (int j = 0; j < data.size(); ++j) {
if (j != i && data[j] % 2 == 0) {
result += val + data[j];
}
}
}
return result;
}
void addData(int d) {
data.push_back(d);
}
};
#include <iostream>
int main() {
DataProcessor dp;
dp.addData(1);
dp.addData(2);
dp.addData(3);
dp.addData(4);
std::cout << dp.processData() << std::endl;
return 0;
}Expected output
30
Core concepts
Challenge a Friend
Send this duel to someone else and see if they can solve it.