extract common code to function