Refactored the code by extracting common code into a private method.