Refactored duplicate code by puting it into a method