extract repeated code to function expressions

Change-Id: I14619cabb8e6a1d8c41ba04072b2ebf45a1c5bc5