Refactor aggregate function