Tree views - Best design practices
Jonathan Gardner
jgardner at jonathangardner.net
Thu Jan 8 15:35:36 EST 2009
On Jan 8, 8:16 am, MRAB <goo... at mrabarnett.plus.com> wrote:
> Filip Gruszczyński wrote:
> > Hi!
>
> > I have certain design problem, which I cannot solve elegantly. Maybe
> > you know some good design patterns for this kind of tasks.
>
> > Task:
>
> > We have a model which has two kinds of objects: groups and elements.
> > Groups can hold other groups (subgroups) and elements. It's a simple
> > directory tree, for example. We would like to display it in a tree
> > view (which sound good for this kind of model). What is more required,
> > for groups and elements there are different sets of operations, which
> > should be available under right click. For example for group, there
> > should be operations: 'add element' and 'add group', and for element
> > there should be 'change properties'.
>
> > Do you know any smart way to achieve this? The simplest way is to ask
> > for the class and display operations accordingly. But from the first
> > day with OO programming I have heard, that asking for class is wrong.
> > But I can hardly see any easy and more maintainable solution for this
> > problem. Could you help me with this?
>
> You could ask the object what the operations are. Here's an example
> using strings:
>
> >>> class Element(object):
> operations = "Element operations"
>
> >>> class Group(object):
> operations = "Group operations"
>
> >>> e = Element()
> >>> g = Group()
> >>>
> >>> e.operations
> 'Element operations'
> >>> g.operations
> 'Group operations'
When faced with this kind of scenario, I usually write boolean methods
like "is_leaf" or "is_branch".
class Element(object):
@staticmethod
def is_leaf(): return True
@staticmethod
def is_branch(): return False
class Group(object):
@staticmethod
def is_leaf(): return False
@staticmethod
def is_branch(): return True
Of course, you have to give priority to one or the other, in case an
object thinks it is both.
if thing.is_branch():
# Treat it like a branch
elif thing.is_leaf():
# Treat it like a leaf
I believe this is a simpler method than checking a single attribute
for a name.
More information about the Python-list
mailing list