I have entity with a list of value object like this:
(I'm using Go, but I hope it generally makes sense)
// this is my Crop entity
type Crop struct {
UID uuid.UUID
Name string
Type string
Notes []CropNote // This is a list of value object.
}
// This is my CropNote value object
type CropNote struct {
Content string
CreatedDate time.Time
}
I have Crop behaviour for AddNewNote(content string)
. But the business process needs to have remove note behaviour too. I'm thinking something like RemoveNote(content string)
behaviour. So I will iterate my Crop.Notes
, find the row with the same content
, then remove that row from the Crop.Notes
list. But I think that finding the value by its note's content is error-prone. And its weird from the API point of view too because I need to send the content to the params.
My question is, how can I implement my Remove Note behaviour above?
EDIT: Sorry I think I'm not clearly explain myself.
I know how to remove a value from a slice.
My issue is about the DDD. About how to remove Value Object that only have fields above from the Crop.Notes
list. Because we know that Value Object cannot have Identifier.
And if I really can only use Content
and CreatedDate
fields from my Value Object, then I should send that Content
or CreatedDate
value to the endpoint when I do REST API request which is weird.
Just use the instance of CropNote itself :
/* sorry for sudo code, not up with GO */
func (c Crop) removeNote(noteToRemove CropNote) {
c.Notes= c.Notes.RemoveItem(noteToRemove); /* RemoveItem() is your own array manipulation code */
}
Now its up to your Application layer to identify and call the removal of the note.
Additional thing to think about:
Why is crop notes part of the Crop aggregate root? is the behavior of a Crop influenced by the notes or does Crop behavior influence the notes? Don't try and rebuild your data model inside your domain, it wont make sense. If your system requires the independent adding/removing/updating of crop notes, they may work better as their own aggregate roots that are indirectly dependent on an existing crop entity eg:
/*again, not proficiant with GO - treat as sudo code */
private type CropNote struct {
UID uuid.UUID
CropUID uuid.UUID
Content string
CreatedDate time.Time
}
function NewCropNote(crop Crop, content string) *CropNote{
cn := new(CropNote)
cn.UUID = uuid.new()
cn.CropUID = crop.UUID
cn.CreatedDate = now()
cn.Content = content
return cn
}
In addition to @WeiHuang 's answer: If your notes is an unordered list, you can use swap instead of append
or copy
.
func (c Crop) removeNote(content string) {
j:=len(c.Notes)
for i:=0;i<j;i++ {
if c.Notes[i]==content {
j--
c.Notes[j],c.Notes[i]=c.Notes[j],c.Notes[i]
}
}
c.Notes=c.Notes[:j]
}