Code refactoring and optimization