Writing Testable Functions for Competitive Programming
Learn how to structure your competitive programming solutions so that they are easy to debug and test with custom inputs.
The Secret to Fast Debugging
In competitive programming or technical interviews, you will inevitably write code that fails. How fast you fix that code depends entirely on how testable your functions are.
The Bad Approach: Everything in main
Many beginners write all their logic inside the main function.
int main() {
// read inputs
// 50 lines of complex array manipulation
// print output
}
If this fails, you have to read through the entire block to find the logic error, intertwined with input/output handling.
The Good Approach: Separation of Concerns
Separate your I/O (reading input, printing output) from your logic.
int findMax(vector<int>& arr) {
// logic here
return max;
}
int main() {
// read inputs
int result = findMax(arr);
// print result
}
Why This is Better
- Custom Testing: If the code fails, you can temporarily ignore the
mainI/O and just pass hard-coded arrays intofindMax()to see exactly where it breaks. - Interview Format: Platforms like LeetCode and HackerRank already use this format. You don't write the
mainmethod; you write theSolutionfunction. Practicing this way builds familiarity with interview environments.
Pure Functions
Strive to write "Pure Functions." A pure function relies only on the parameters passed to it and does not modify global variables. This guarantees that if you give it the same input, it will always return the exact same output, making debugging trivial.
The Takeaway
Structure your practice code as if it were a module. Keep logic separate from I/O. This habit will drastically reduce your debugging time during timed contests and interviews.
Mixing input/output handling with algorithmic logic makes the code difficult to read, hard to test with custom inputs, and harder to debug.
It is a design principle where a program is divided into distinct sections, each handling a specific task (e.g., separating data parsing from algorithmic computation).
A pure function is a function that always produces the same output for the same input and has no side effects (like modifying global variables or printing to the console).
They test your code by directly calling the specific function (e.g., 'solve(input)') with various test cases and checking the returned value, completely ignoring I/O.
It shows the interviewer that you understand software architecture. Furthermore, if your main algorithm is isolated in a function, you can write small test cases to prove it works.
