I am trying to standardize the logic of a class.clone method so that every child of my abstract class clones the exact same way.
I’ve tried using factory constructors and all sorts of roundabouts but I can’t seem to find a solution that doesn’t require adding an additional function specifically for cloning, which I feel is redundant and opens me up to unwanted variance in how cloning works down the line.
The class structure is as follows:
abstract class ParentClass<T extends ParentClass<T>> {
String foo;
int bar;
Model({
String? foo,
int? bar
Map? kwargs,
}) : foo = foo ?? kwargs?['foo'] ?? "Not provided",
bar = bar ?? kwargs?['bar'] ?? 0;
Map<String, dynamic> toMap();
// toMap always returns approximately {'foo':foo1, 'bar':bar1, "x":x1, etc.}
T clone();
//Optimally along the lines of T clone() => T(kwargs:toMap())
}
2
Answers
Thanks ApaxPhoenix for pointing me in the right direction.
The copy pattern seems like a good practice generally but in my case there are properties of the child class which also need to be cloned by the same method. What I ended up doing is changing every child class to pass its own default constructor to itself since I know they all must follow the same system of
x = x ?? kwargs['x']
This allows
childClass.clone
to automatically returnchildClass(kwargs: toMap)
no matter what childClass, as long as its specified again in the constructor. Still requires extra work but ensures no variance in how cloning operates.Seems a little dirty to me so open for suggestions to optimize.
To standardize the
clone
method for every child of your abstract classParentClass
, you can utilize a pattern called the "copy constructor" pattern. This pattern involves adding a constructor to your abstract class that takes an instance of the same class as an argument and creates a new instance based on the properties of the provided instance. Here’s how you can implement it in your code:With this implementation, you’ve added a copy constructor to your abstract class
ParentClass
. This copy constructor takes an instance of the same class as an argument and initializes the new instance with the properties of the provided instance. Theclone
method in your abstract class now simply calls this copy constructor to create a new instance of the same type with the same properties.