Extract duplicated code into one function