Better way to write this function