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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With