merge two parts of similar codes to a method