Search code examples
pythonoopfunctional-programmingloose-couplingcohesion

Which is "better" practice? Passing object references or object method references in Python


I'm writing a small piece of code in Python and am curious what other people think of this.

I have a few classes, each with a few methods, and am trying to determine what is "better": to pass objects through method calls, or to pass methods through method calls when only one method from an object is needed. Basically, should I do this:

def do_something(self, x, y, manipulator):
    self.my_value = manipulator.process(x, y)

or this

def do_the_same_thing_but_differently(self, x, y, manipulation):
    self.my_value = manipulation(x, y)

The way I see it, the second one is arguably "better" because it promotes even looser coupling/stronger cohesion between the manipulation and the other class. I'm curious to see some arguments for and against this approach for cases when only a single method is needed from an object.

EDIT: I removed the OOP wording because it was clearly upsetting. I was mostly referring to loose coupling and high cohesion.


Solution

  • The second solution may provide looser coupling because it is more "functional", not more "OOP". The first solution has the advantage that it works in languages like C++ which don't have closures (though one can get a similar effect using templates and pointer-to-member-functions); but in a language like Python, IMHO the 2nd alternative seems to be more "natural".

    EDIT: you will find a very nice discussion of "functional vs. object oriented" techniques in the free book "Higher order Perl", available here:

    http://hop.perl.plover.com/

    (look into chapter 1, part 6). Though it is a Perl (and not a Python) book, the discussion there fits exactly to the question asked here, and the functional techniques described there can be applied to Python in a similar way.