Structure code based on what it does rather than how it’s implemented. Group related functionality together, extract reusable components, and place code in appropriate packages or files to improve maintainability and readability.

Key principles:

Example of good organization:

// Instead of having everything in one large function
func (s *recordingPlayback) streamEvents(ctx context.Context, req *fetchRequest, ...) {
    // 200+ lines of complex logic with nested processEvent function
}

// Extract for better readability
func (s *recordingPlayback) streamEvents(ctx context.Context, req *fetchRequest, ...) {
    // Main orchestration logic
    for event := range eventsChan {
        if !s.processEvent(event, req) {
            break
        }
    }
}

func (s *recordingPlayback) processEvent(evt apievents.AuditEvent, req *fetchRequest) bool {
    // Focused event processing logic
}

This approach makes code easier to understand, test, and maintain by creating clear boundaries between different responsibilities.