Refactor by moving function closer to their usage