On Thu, Jun 16, 2011 at 2:07 PM, Micky Hulse <rgmi...@gmail.com> wrote:
> Hello, > > Just curious what the rule-of-thumb is for when it comes to using > model methods vs. properties. For example: > > [code] > > @property > def is_modified(self): > if self.modified > self.created: > return True > return False > > def get_separator(self): > return ' :: ' > > [/code] > > I feel like I have seen so many examples of methods and properties > that return the same type of stuff, I am just confused about when to > use one over the other. > I tend to avoid @property -- it adds conceptual overhead for code readers (hiding the fact that a function call is taking place) for little gain. The main use for @property is backwards-compatibility: if my code used to have an attribute, and I now need to compute something instead of returning an attribute directly, I'll use @property so that calling code doesn't need to change. Beyond that, my preferred rule of thumb is that I will not use @property if any non-trivial computation takes place. But I try to avoid it even for trivial computations. Methods are more self-documenting and more flexible (e.g. less refactoring needed if you end up adding function arguments later) The one exception is adaptation. If I have a method that returns another object that's an API wrapper which I'll be accessing immediately, I'll use @property -- e.g. class MyModel(models.Model): @property def printer(self): return Printer(self) class Printer(object): def __init__(self, inst): self.inst = inst def get_value(self): return "something" def print(self, out): out.write( str(self.inst) + self.get_value() ) In a case like this I use property so that I can write `myobject.printer.print(foo)` instead of `myobject.printer().print(foo)` which just looks too ugly for me to ignore. For your lat/lng example I'd probably just write a single model method (not a property) that parses the CharField and returns a 2-tuple (lat, long) and another which sets them given two arguments. (How often do you use one without the other, anyway; the fact that they're conceptually coupled seems more likely to survive refactoring than the storage mechanism and format.) -Ethan -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.