re-factor out duplicate code to use template