Algorithms should handle their own state initialization and cleanup internally rather than relying on callers to manage it. This prevents bugs caused by stale data from previous executions and reduces the burden on calling code.
Algorithms should handle their own state initialization and cleanup internally rather than relying on callers to manage it. This prevents bugs caused by stale data from previous executions and reduces the burden on calling code.
When designing algorithms that maintain state between calls or process hierarchical data structures, ensure that:
Example from layout algorithm:
function layoutNode(node, parentMaxWidth, parentDirection) {
// Algorithm handles its own state reset internally
if (!node.lastLayout) {
node.lastLayout = {};
}
// Reset child layouts internally rather than requiring caller to do it
// This prevents stale position data from affecting current calculations
resetChildLayouts(node);
// Continue with algorithm logic...
}
This approach prevents issues where “isUndefined checks might fail where they shouldn’t” and ensures “the callsite doesn’t have to care and possibly introduce bugs” by forgetting to reset state properly.
Enter the URL of a public GitHub repository