Is there a way to make this code more effective?