dimanche 15 octobre 2017

Creational Pattern in Python

I have some different object to build. Some of them I need to make a validation (for example: see if it exists on the database - see code below).

What kind of pattern could i use? Façade for separate the complexity of create a new object?

Is it a good practice to put validation rules on the "factory" class?

Can someone propose a different approach?

class CheckoutInput:

    def __init__(self, checkout_input, session):
        self.checkout_input = checkout_input
        self.session = session

    def build_delivery(self):
        delivery_id = self.checkout_input.get('poc_delivery_type_id')
        poc_delivery = self.session.query(
            model.POCDeliveryType.id == delivery_id).first()
        if (poc_delivery):
            return Delivery(delivery_id, poc_delivery.price, poc_delivery.active)
        else:
            return Delivery(delivery_id)

    def build_cart(self):
        line_items = self.checkout_input.get('line_items', [])
        token = self.checkout_input.get('cart_token')
        cart = Cart(token)
        for item in line_items:
            inventory_item_id = item.get('inventory_item_id')
            quantity = item.get('quantity')
            item_model = self.session.query(model.InventoryItem).filter(
                model.InventoryItem.id == inventory_item_id).first()
            if (item_model):
                poc = POC(item_model.poc.id, item_model.poc.timezone) if (
                    item_model.poc) else None
                line_item = LineItem(
                    inventory_item_id, quantity, item_model.price, item_model.quantity, poc)
            else:
                raise Exception(
                    'Invalid inventory id: {}'.format(inventory_item_id))
            cart.add(line_item)
        return cart

Aucun commentaire:

Enregistrer un commentaire