Refactoring and code optimization