Passing Functions vs Objects as Arguments

109 views
Skip to first unread message

Karan Gajwani

unread,
Jun 7, 2013, 12:04:19 PM6/7/13
to growing-object-o...@googlegroups.com
Hi,

I came across passing functions into method parameters in python. 

In terms of readability, reasoning, and good coding style practice, I was wondering if it was better / worse / indifferent to passing objects.

Eg. 

Say we have a method that needs to create a car:

def createCar(wheelFactory, ...):
  ...
  car.frontWheel = wheelFactory.createWheel()
  ...


vs.

def createCar(createWheel, ...):
  ...
  car.frontWheel = createWheel()
  ...

Thanks!


Nat Pryce

unread,
Jun 7, 2013, 5:33:13 PM6/7/13
to growing-object-o...@googlegroups.com
In Python almost everything is an object and is invoked polymorphically -- functions, modules, builtin types, user-defined types, you name it. So it's common to pass them around directly, and create new types that have the same interface if you need to pass in different (but compatible) behaviour.

For example, I rarely write factory functions because classes are themselves first-class objects and callable like functions. So if I need to parameterise a function by the type of object it should create, I'll pass the class of object to the function. If I need to do something more than just create a new object, I can define a function that has the same signature as the classes' constructors and pass that in. Or a lambda expression. Or a method on a class and pass a bound-method in that invokes the method on a specific instance. Or an object that implements __call__. Or ... 

Python gives you loads of options to write flexible code and/or shoot yourself in the foot.

My rule of thumb is that if an object needs to invoke different operations on a peer, it's easier to pass a peer object than multiple peer functions. Otherwise I'll pass a single function because it makes using the class easier.

--Nat
--
 
---
You received this message because you are subscribed to the Google Groups "Growing Object-Oriented Software" group.
To unsubscribe from this group and stop receiving emails from it, send an email to growing-object-oriente...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

Karan Gajwani

unread,
Jun 9, 2013, 6:17:15 PM6/9/13
to growing-object-o...@googlegroups.com
Makes sense.

Thanks Nat! 
To unsubscribe from this group and stop receiving emails from it, send an email to growing-object-oriented-software+unsubscribe@googlegroups.com.
Reply all
Reply to author
Forward
0 new messages