Andrea Koutifaris
2 min readJul 28, 2020

--

This is not related just to factories. Every time there is an external input that needs to be associated to a programming entity (Class for example) there are always 4 ways:

- if/else

- switch

- Maps (A.K.A. Dictionaries)

- Reflection, which can use an Interface declaration with all the cars instead of a dictionary.

They are similar ways, and the Map version saves some lines of code in JavaScript, because declaring a map is as simple as writing {key: 'value'}.

Your version is OK, but it still violates Open/Close in the same way the others do, because you need somewhere (ConfigureServices) to associate car types to factory methods. Each time there is a new car type, that part of the code needs to be changed. Like in the if/else switch case.

Of course, as you point out in the article, each version has some pros and cons and your version works well with the example of a web application.

Anyway the Dictionary/Map solution wouldn't violate the open close and if there were only a Car class that could work with car data coming from a json, for example. In that case the dictionary would contain instances or factory methods with the specific data already set from a bootstrapping code that reads the data somewhere (Eg. files in a directory) and adds the car models to the dictionary.

It is better to avoid using any of the mapping methods above when there is no need. If the input does not come from a serialized source outside of the program, there is no need to map a string to a factory method.

For example, if the user press the "Create ellipse" icon button in a graphical editor, the code can directly call createEllipse(...) in an abstract factory, instead of calling create('Ellipse').

--

--

Andrea Koutifaris
Andrea Koutifaris

No responses yet