Refractor code to remove duplicate lines