Considering if there is a best practice here.
It seems that abstract methods produce a cleaner visual interface when implementing them in a child class. However, it seems that does involve some extra code boilerplate
With the constructor approach, you can specify the unique ID with just a variable. However, it requires that you call the super constructor, which otherwise, you don't have to (in this example anyway)
Just wondering if there is anything objective here that I am missing. Because both are encapsulating what varies in the child class.
// Enum
enum Id {
A,
}
// Abstract class requiring subclasses to implement method returning their ID
abstract class Abstract_Method {
abstract id(): Id;
log() {
console.log(this.id());
}
}
// Abstract class requiring subclasses to call the super constructor and specify their ID
abstract class Abstract_Constructor {
id: Id;
constructor(id: Id) {
this.id = id;
}
log() {
console.log(this.id);
}
}
// Child classes
class Child_Method extends Abstract_Method {
id(): Id {
return Id.A;
}
}
class Child_Constructor extends Abstract_Constructor {
constructor() {
super(Id.A);
}
}
// Test
new Child_Method().log();
new Child_Constructor().log();
Aucun commentaire:
Enregistrer un commentaire