Let’s say I have a class hierarchy. I could theoretically maintain its functionality with a single class, by providing extra parameters to the instances. Here’s an example (super-contrived, but I wanted to keep it simple):
class Base:
def __init__(self, a):
self.a = a
def f(self, x):
raise NotImplemented # needs to be defined in subclass
class Mult(Base)
def f(self, x):
return self.a * x
class Add(Base):
def f(self, x):
return self.a + x
m = Mult(5)
a = Add(7)
m.f(10)
a.f(20)
The above code can be refactored as:
class Compute:
def __init__(self, a, func):
self.a = a
self.func = func
def f(self, x)
return self.func(self.a, x)
m = Compute(5, operator.mult)
a = Compute(7, operator.add)
I understand that for this silly example, it makes no difference. So please don’t think about it except to understand my point.
I want to know what factors I should think about when making this choice for the variety of situations I encounter in real life? In other words, what are the pros / cons of using classes versus parameterized instances?
In the first example, you supply the client code with canned ways of doing a fixed set of operations. It’s easy to multiply, but if you want to divide instead, well, tough luck.
In the second example, you push implementation details up to the client. You now have an entire operation-agnostic computation framework. This requires more knowledge in the client code.
So, what really differs is the level of abstraction—how knowledgeable you want your client to be. If it is important for the client that
operator.multbe used, not some other logic (like, XML-RPC to a multiplication server), the second option seems appropriate. If the client knows better than you what to do with the two numbers, and you want to provide only a framework (a wrapper of sorts), the second option is better. If you just want to let people add and multiply stuff, the first option is better.