dimanche 14 mai 2017

How to handle behavioral changes of a model after introducing a new field?

I have a model/class with it's own methods to calculate some data. Recently i have to introduce a new boolean/choice field is_producing, based on that field calculation will be changed in multiple places, especially on property methods. Like below example:

class Lease(models.Model):
    name = models.CharField(max_length=250)

    @property
    def owner_count(self):
        return 27 # for example


class Lease(models.Model):
    name = models.CharField(max_length=250)
    is_producing = models.BooleanField(default=True)

    @property
    def owner_count(self):
        if self.is_producing:
            return 27 # for example
        else:
            return 20 # for example

class Offer(models.Model):
    lease = models.ForeignKey(Lease)
    amount = models.FloatField()

    def save(self):
        if self.lease.is_producing:
            self.amount = 100 # For Example
        else:
            self.amount = 200

It seems that using if/else in all places is anti-pattern and not intuitive. On the other hand, if we create a new model with that new field, it will duplicate a lot of code and relate models.

So i am looking for design pattern which can solve the above scenario or any other elegant solution that would solve it with less code duplication.

Aucun commentaire:

Enregistrer un commentaire