如何处理域实体的必需属性? [英] How to handle required properties for Domain Entities?

查看:89
本文介绍了如何处理域实体的必需属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个UserEntity,根据它的id属性,该实体最终保留在数据库中.在这种情况下,id属性显然是敏感的,因为更改它会导致UserEntity在以后持久保存时保存在另一个UserEntity上.

I have a UserEntity that is eventually persisted in the DB according to it's id property. In this case, the id property is obviously sensitive, because changing it would cause the UserEntity to be saved over a different UserEntity when persisted later.

因此,我想帮助您防范此类情况的发生...

I would therefore like to help safe guard against something like this happening...

选项1.我是否强制将id传递给构造函数,从而删除了Setter?

Option 1. Do I FORCE the id to be passed into the constructor, thereby removing the Setter?

  • 这意味着存储库被赋予持久性的每个UserEntity都是有效的(因为它具有id的最低要求).
  • 缺点是我的控制器无法创建新的UserEntity(),因为它没有id来提供它.
  • This would mean that every UserEntity that the Repository is given to persist will be valid (because it has the minimum requirement of an id).
  • The downside is that my Controller wouldn't be able to create a new UserEntity() because it wouldn't have an id to give it.

选项2.允许构造函数中的ID为空,但不提供设置器

  • 这实际上将创建两种类型的UserEntity对象:已持久的和未持久的.
  • 我可以在任何地方创建新的UserEntity(),并用它的值填充它,然后传递给存储库,后者将对其进行保存,并使用新的id创建一个新的UserEntity,然后将其还给我.
  • 这很酷,但是这意味着我需要仔细检查我的实体在要用于持久化/域逻辑/等操作的任何地方都有一个id,以确保它是一个保存的实体.
  • This would essentially create two types of UserEntity objects: ones that have been persisted, and ones that haven't.
  • I could do new UserEntity() anywhere, fill it with it's values, then pass to the Repository who would then save it, create a new UserEntity with the new id, and give it back.
  • This is cool, but means I need to double check that my entity has an id anywhere that I want to use it for persisting / domain logic / etc, to make sure that it is a saved entity.

选项3.我不必担心太多,并为此提供一个机会吗?

  • 这暴露了更改UserEntity的id并覆盖数据库中其他UserEntity的风险.
  • 从好的方面来说,我可以在不知道id的情况下创建一个新的UserEntity(),然后将其传递到我的存储库进行保存.
  • This exposes the risk of changing the id of a UserEntity, and overwriting a different UserEntity in the db.
  • On the upside, I can create a new UserEntity() without knowing the id ahead of time, which I can pass to my Repository for saving.

推荐答案

如果您关心域对象的有效性,则需要始终确保有效性.

If you care about the validity of your domain objects, you need to ensure validity in all times.

这意味着您不对不希望直接更改的属性提供设置器,而是使用指定的方法来改变其状态.

This means that you don't provide setters on properties that you do not want changed directly, but use specified methods to mutate their state.

如果示例中的id从未更改,则应仅在构造函数中进行设置(并强制将其传递).

If the id in your example never changes, you should only ever set it in the constructor (and enforce it being passed in).

这篇关于如何处理域实体的必需属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆