refactor code (complete code)