【问题标题】:DDD Remove a Text Value Object from A List of Value ObjectDDD 从值对象列表中删除文本值对象
【发布时间】:2018-01-15 04:27:20
【问题描述】:

我有一个具有如下值对象列表的实体:
(我正在使用 Go,但我希望它通常是有意义的)

// 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
}

我有 AddNewNote(content string) 的裁剪行为。但是业务流程也需要具有删除注释行为。我在想类似RemoveNote(content string) 的行为。所以我将迭代我的Crop.Notes,找到具有相同content 的行,然后从Crop.Notes 列表中删除该行。但我认为通过笔记的内容来寻找价值是容易出错的。从 API 的角度来看,这也很奇怪,因为我需要将内容发送到参数。

我的问题是,如何实现上面的删除注释行为?

编辑: 对不起,我想我没有清楚地解释自己。
我知道如何从切片中删除值。
我的问题是关于 DDD。关于如何从Crop.Notes 列表中删除仅具有上述字段的值对象。因为我们知道值对象不能有标识符。
如果我真的只能使用值对象中的ContentCreatedDate 字段,那么我应该在执行REST API 请求时将ContentCreatedDate 值发送到端点,这很奇怪。

【问题讨论】:

    标签: go domain-driven-design value-objects


    【解决方案1】:

    只需使用 CropNote 本身的实例即可:

    /* 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 */
    }
    

    现在由您的应用程序层来识别和调用便笺的删除。

    需要考虑的其他事项:

    为什么作物注释是作物聚合根的一部分? Crop 的行为是否受到音符的影响,或者 Crop 的行为是否影响音符?不要尝试在您的域内重建您的数据模型,这没有任何意义。如果您的系统需要独立添加/删除/更新作物注释,它们可能会更好地作为它们自己的聚合根,间接依赖于现有的作物实体,例如:

    /*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
    }
    

    【讨论】:

      【解决方案2】:

      除了@WeiHuang 的回答: 如果你的笔记是一个无序列表,你可以使用 swap 代替 appendcopy

      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]
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-08-03
        • 2019-07-02
        • 2014-06-03
        • 2011-06-15
        • 1970-01-01
        • 2010-10-04
        相关资源
        最近更新 更多