vendredi 24 juillet 2020

How do I instantiate a child class in a default method of an immutable abstract base class?

How do I instantiate a child class in a default method of an immutable abstract base class e.g. return a new instance with modified properties?

I have an abstract document class with a few properties which is immutable. When calling the createDocument or updateDocument methods, a new instance should be returned with the fields set to the new values. I don't want to override the methods in each child class since the logic will remain the same => duplicate code. Is there a way / pattern to get around this problem or am i simply missing something here?

abstract class Document extends Model {
    final Version version;
    final Id id;
    final DateTime createdAt;
    final DateTime modifiedAt;

    Document(this.version, {this.id, this.createdAt, this.modifiedAt})

    Document createDocument(Id id, DateTime timestamp) {
        // some validation logic here
        // TODO 
        // Instantiate a new document and set the id, createdAt fields 
    }

    Document updateDocument(DateTime timestamp) {
        // some validation logic here
        // TODO 
        // Instantiate a new document and set modified at field
    }
}

class User extends Document {
    static const Version VERSION = Version(1,0,0);
    final int someProperty;
    User(this.someProperty) : super(VERSION)

}

One idea of mine was to implement an abstract copyWith method

  Document copyWith({Id id, DateTime modifiedAt, DateTime createdAt});

but that would mean that other classes can access the copy method and set arbitrary values which would defeat the whole purpose of the validation logic in the methods and it would inflate the code. Furthermore since I'm using Dart I can not really use protected methods.

Any help would be highly appreciated!

Aucun commentaire:

Enregistrer un commentaire