Refactoring code to remove duplicate code with extract to new function