dimanche 23 juillet 2017

How much business code is ok to have in a Factory?

I'm learning patterns using problems that actual I have. So, sorry for some too basic questions.

I have a Factory that creates four different types of products:

class ProductFactory:
    def product_a(self):
        return ProductA()

    def product_a(self):
        return ProductB()

    def product_a(self):
        return ProductC()

    def product_a(self):
        return ProductD()

But ProductA is a little bit complex. In fact ProductA is built using two different classes because those are different data sources that actual have to be put together in a intricate way to generate an useful ProductA.

So, my doubt:

Is that ok to have my product_a() method in the ProductFactory to be responsible to mess around with those two data sources, do everything necessary and finally build the neat ProductA? Or product_a() is not supposed to know anything about how ProductA is mounted using a considerable business logic?

For example, only a illustration, my ProductA would look something like:

    class ProductFactory:

        def __init__(self, data_source1=None, data_source2=None):
            self.data_source1 = data_source1
            self.data_source2 = data_source2

        def product_a(self):

            formated_data = self.data_source1.do_creepy_stuff()
            messed_data = self.data_source2.mess_a_lot()

            final_data = formated_data.update(messed_data)

            return ProductA(final_data)

        def product_b(self):

            return ProductB()

if __name__ == "__main__":

    data_source1 = DataSource1('my_file')
    data_source2 = DataSource2('my_directory')

    factory = ProductFactory(data_source1, data_source2)

    product = factory.product_a()

In case that idea is ok, would be better to pass the data sources as parameter to the product_a() method or as parameter to the factory constructor (like in example)?

In general... I'm very confused to let the factory having the responsibility to know how to execute methods from those data sources (like data_source1.do_creepy_stuff())... I guess any change in my data sources classes could contaminate my factory.

But at the same moment, I actual have a ProductA that uses to different data sources as its parts AND those data sources have to be manipulated before mounting ProductA, by the simply fact those data sources are also used by other parts of the software that has nothing for to do with products.

So, I'm really working hard to understand the best way to deal with that situation and a factory seem to be the best solution, but... there's those doubts...

Thank you for any help!!

Aucun commentaire:

Enregistrer un commentaire