Refactored duplicate code into helper function