Refactored code generation logic