lundi 1 avril 2019

How to avoid designing classes whose member functions depend on each other?

Let's say I have a class called Adder:

Class adder(object):
  def __init__(self, a, b):
     self.a=a
     self.b=b
     self.result = None

  def perform_addition(self):
     self.result = self.a + self.b
     return self.result

If I instantiate this class:

myAdder = adder(1,2)

Then the value of myAdder.result depends on calling perform_addition() first, otherwise it'll always remain None. It other words, there's a dependency on perform_addition() for the value of self.result. And if we extrapolate, a more complex class can have a chain of dependencies: ie, you have to call functions A, B, and C before D, because they in turn populate the necessary variables that the next function needs.

Is this bad class design? What is the remedy for it? I think the above is a example of: https://en.wikipedia.org/wiki/Sequential_coupling

Aucun commentaire:

Enregistrer un commentaire