Factor duplicated code