1

我需要理解这段代码,resoCoder 是在 DDD 播放列表上完成的。为什么他在冻结的内部实现 IEntity?

代码是:

@freezed
abstract class TodoItem with _$TodoItem implements IEntity {
  const factory TodoItem({
    @required UniqueId id,
    @required TodoName name,
    @required bool done,
  }) = _TodoItem;

  factory TodoItem.empty() => TodoItem(
        id: UniqueId(),
        name: TodoName(''),
        done: false,
      );
}
}

IEntity 代码是:

abstract class IEntity {
  UniqueId get id;
}

UniqueId 代码为:

class UniqueId extends ValueObject<String> {
  @override
  final Either<ValueFailure<String>, String> value;

  // We cannot let a simple String be passed in. This would allow for possible non-unique IDs.
  factory UniqueId() {
    return UniqueId._(
      right(Uuid().v1()),
    );
  }

  /// Used with strings we trust are unique, such as database IDs.
  factory UniqueId.fromUniqueString(String uniqueIdStr) {
    assert(uniqueIdStr != null);
    return UniqueId._(
      right(uniqueIdStr),
    );
  }

  const UniqueId._(this.value);
}
4

1 回答 1

1

它确保一致性;TodoItem 必须按照 IEntity 实现所有内容。

假设有一天您想向 IEntity 添加一个属性“createdAt”:在这种情况下,您必须将“createdAt”添加到整个项目中实现 IEntity 的每个类,否则编译器会让您知道您遗漏了一些东西:D


现在一些代码。

结果将是

abstract class IEntity {
  UniqueId get id;
  int get createdAt; // let's keep it "int" for the example purpose
}

那么你也必须更新冻结的课程

@freezed
abstract class TodoItem with _$TodoItem implements IEntity {
  const factory TodoItem({
    @required UniqueId id,
    @required int createdAt,
    @required TodoName name,
    @required bool done,
  }) = _TodoItem;

  factory TodoItem.empty() => TodoItem(
        id: UniqueId(),
        createdAt: 1234,
        name: TodoName(''),
        done: false,
      );
}
}
于 2021-10-22T08:13:41.513 回答