什么时候在冻结中实现抽象 class?

when to implements an abstract class in freezed?

我需要理解这段代码,resoCoder 在 DDD Playlist 上做到了。为什么他在 freezed 里面实现了 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,
      );
}
}

实体代码为:

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);
}

保证一致性; TodoItem 必须按照 IEntity 实施所有内容。

假设有一天您想要向 IEntity 添加一个属性“createdAt”:在这种情况下,您必须向每个 class 在项目中实现 IEntity 添加“createdAt”,否则编译器会让你知道你错过了什么 :D


现在一些代码。

结果会是

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

那么你也必须更新冻结的class

@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,
      );
}
}