Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Classes versus parameterized instances

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?

like image 652
max Avatar asked Sep 24 '26 23:09

max


2 Answers

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.mult be 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.

like image 75
Vasiliy Faronov Avatar answered Sep 26 '26 13:09

Vasiliy Faronov


It really depends on what the classes do. In your example the logic in the classes it so minimal it is obvious you've just supplied wrappers for methods as classes. and it makes more sense to have the compute class.

In real life situations you should ask yourself how cohesive are the different functions you want to group together. Though single responsibility is important you don't need to take that ad absurdum

like image 39
Arnon Rotem-Gal-Oz Avatar answered Sep 26 '26 12:09

Arnon Rotem-Gal-Oz