merge similar codes into function