我有聚合
ExampleEntity1
与 ExampleEntity1ID
以及 ExampleEntity2
与 ExampleEntity2ID
。 ExampleEntity2
通过使用ExampleEntity1
来指代ExampleEntity1ID
。 ExampleEntity1
和 ExampleEntity2
位于不同的有界上下文中。在这种情况下,我可以在第二个上下文中从第一个上下文导入ExampleEntity1ID
,还是应该在第二个上下文中重新定义ExampleEntity1ID
?如果我需要在 2 个不同的上下文中使用相同的 id,我该怎么办?
示例:
/domain/context_1/models.py
class ExampleEntity1ID:
value: str
class ExampleEntity1:
id: ExampleEntity1ID
some_field_1: str
/domain/context_2/models.py
from domain.context_1 import ExampleEntity1ID
class ExampleEntity2ID:
value: str
class ExampleEntity2:
id: ExampleEntity2ID
example_entity_1_id: ExampleEntity1ID
some_field_2: str
或者重新定义它
class ExampleEntity1ID:
value: str
class ExampleEntity2ID:
value: str
class ExampleEntity2:
id: ExampleEntity2ID
example_entity_1_id: ExampleEntity1ID
some_field_2: str
你应该考虑重复自己(打破DRY在这里是较小的罪恶!)。首先,根本不建议引用其他有界上下文。在最坏的情况下,您应该创建一个共享内核来重用有界上下文之间的结构。但是,在此示例中您不需要它。因为更改实体的 ID 表示的可能性很低。所以我个人认为重写结构会更好。另一方面,更改 ID 需要谨慎操作并与其他团队协调。结果,改变得如此大胆,你不会错过改变重复的代码(DRY想要解决的问题)。