I have two classes: Foo
and Bar
and I have a dictionary (coming from reading a JSON file) that specifies if an entry is of class Foo or class Bar
myDict = {
"Alice": "Foo",
"Bob": "Bar"
}
What I’m currently doing is to use a conditional to either create a Foo or a Bar instance.
let instances = [];
for (const [name, className] of Object.entries(myDict)) {
if (className == "Foo") {
instances.push(new Foo(name));
}
else if (className == "Bar") {
instances.push(new Bar(name));
}
}
However, I expect the number of class types to increase in a future, meaning that I will create new classes (eg: Baz
) but I don’t want to have to modify the code of the conditional to add new else cases.
Is there a better way?