Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should a modifying class method save itself or be explicity called after the method is called?

Tags:

python

django

Suppose a class has a method that modifies it's internals. Should that method call save on itself before returning or should the save be left to the caller to explicitly save after the modifying method has been called?

Example:

Explicitly calling save:

class Bar(models.Model):
    def set_foo(self, foo):
        self.foo = foo

bar = Bar()
bar.set_foo("foobar")
bar.save()

or allowing method to call save:

class Bar(models.Model):
    def set_foo(self, foo):
        self.foo = foo
        self.save()

bar = Bar()
bar.set_foo("foobar")

I'm working with django, but I was wondering if there was a best practice in django or in general for this situation.

like image 966
Simplecoder Avatar asked Jun 26 '10 19:06

Simplecoder


2 Answers

The user of your API might want to make several changes, saving the object after every change is anything but good so no, don't call save in your method.

like image 163
DasIch Avatar answered Nov 09 '22 20:11

DasIch


The user of your API might forget to call .save() and then get screwed. So I think its better to call save for him. For cases like those Daslch mentions, if it makes sense, you can define:

def set_foo(self, foo, skip_save=False):
    self.foo = foo
    if not skip_save:
        self.save()

so the user can, if she wishes to (and explicitly states that), avoid the save.

like image 45
Ofri Raviv Avatar answered Nov 09 '22 20:11

Ofri Raviv