When you identify duplicate code blocks, complex logic that can be simplified, or functionality that doesn’t belong in its current location, extract it into well-named, reusable functions. This improves code organization, reduces duplication, and enhances readability.

Key scenarios to apply this practice:

Example transformation:

// Before: Complex inline logic
if req.Event != busv1alpha1.PodPendingEvent {
    cc.delayActionMapLock.Lock()
    if taskMap, exists := cc.delayActionMap[key]; exists {
        for podName, delayAct := range taskMap {
            // 20+ lines of complex cancellation logic
        }
    }
    cc.delayActionMapLock.Unlock()
}

// After: Extracted function
if req.Event != busv1alpha1.PodPendingEvent {
    cc.cancelDelayedActions(key, req)
}

func (cc *jobcontroller) cancelDelayedActions(key string, req *Request) {
    cc.delayActionMapLock.Lock()
    defer cc.delayActionMapLock.Unlock()
    // Clear, focused cancellation logic
}

This practice makes code more maintainable, testable, and easier to understand by giving complex operations descriptive names and clear boundaries.