EasyPro challengePythonJavaScriptTypeScript
Command-Query Separation
Clean CodeCQSRefactoring
A function should either do something (command) or answer something (query) — never both.
// dirty — modifies AND returns a value in the same function
function solve(stack, value) {
stack.push(value);
return stack.length; // query mixed with command
}Refactor into two separate functions:
push(stack, value)— command: pushes value, returnsnull/voidsize(stack)— query: returns the current length, no mutation
solve(stack, value, 'push') dispatches to push · solve(stack, 'size') dispatches to size.
Sample tests
Test #1push returns void/null (command)
Input: [[],1,"push"]
Output: null
Test #2size returns current length
Input: [[1,2,3],"size"]
Output: 3
Test #3size of empty stack is 0
Input: [[],"size"]
Output: 0