hanki.dev

Don't mutate cached response in Java!

I've done few React projects already and know not to needlessly mutate the state. For some reason I didn't apply the same logic to my Java projects, and struggled quite a bit with the following bug:

@Cacheable(value="cache.value", key="cache.key")
public Animal getAnimal() {
   AnimalData data = getDataFromSomewhere();
   Animal animal = new Animal();
   animal.setName(data.getName());
   animal.setAge(data.getAge());
   return animal;
}

public Animal getYellowAnimal() {
   Animal animal = getAnimal();
   animal.setColor("YELLOW");
   return animal;
}

Since we're directly mutating the Animal object which we get from getAnimal, the yellow color will also be cached. So after you've called getYellowAnimal, every time you call getAnimal you will get yellow animal even if you don't want one!

Here's a simple way to fix this with a copy constructor:

public Animal getYellowAnimal() {
   Animal animal = new Animal(getAnimal());
   animal.setColor("YELLOW");
   return animal;
}

#java