views:

51

answers:

2

I often have functions which take a parameter, set an instance variable to that parameter, and then do other things, e.g.:

def updateFoo(self, foo):
    self.foo = foo
    fooProcessor1(foo)
    fooProcessor2(self.foo)

Do you prefer to pass the parameter itself, as in fooProcessor1, or the newly-set instance variable, as in fooProcessor2? Why or why not?

+1  A: 

Coders should be lazy. self. is way too much to type at 1 am.

Captain Giraffe
+2  A: 

A function named setFoo() really shouldn't do anything more than setting foo unless it is computing and caching a value derived from foo, in which case I would advise something along the lines of:

  def setFoo(self, foo):
      self.foo = foo
      self.__fooUpdated()

  def __fooUpdated(self):
      # Recompute values derived from foo, dispatch signal to listeners, etc.

Of the options you suggested, I prefer fooProcessor1(foo). That said, it is mostly a matter of personal preference. As long as you are consistent, I don't think it matters all that much.

Michael Aaron Safyan
i didn't mean it to just be a setter functoin, these funcs do other things too. changed the func name
Claudiu
@Claudiu - as a matter of style, you are setting `self.foo` and then recomputing things based on the new value of `self.foo`. It may be splitting hairs, but that's not quite the same as recomputing values based on the *parameter* `foo`. Because of that I like Michael's solution here, which separates the concerns.
Stephen P
hmm yeah i see your point.. i like it
Claudiu