My domain entity often looks like this:
class {
rename(string $name): void {
if ($this->name === $name)
return;
$this->name = $name;
$this->recordEvent(new CategoryRenamed($this->id, $this->name));
}
changeDescription(string $description): void {
if ($this->description === $description)
return;
$this->description = $description;
$this->recordEvent(new DescriptionChanged($this->id, $this->description));
}
changeColor(Color $color): void {
if ($this->color->equals($color))
return;
$this->color = $color;
$this->recordEvent(new ColorChanged($this->id, $this->color));
}
}
I have few questions:
Do I have to check that property changed and just return if it didn't?
My goal is to reduce unnecessary code invocations (including database). And also some services may be subscribed to events, so every time event raised - every listeners execute their logic
Do I have to test that event doesn't occur if property didn't change?
At the moment I have two tests for each method: one that event occurs if something changed, second - that event doesn't occur if property didn't change.
What is the best practice for domain entities? And why I should do this?