Wednesday, 15 December 2010

Code Factoring

This is my snippet button handler. It's comment heavy because I kept having to work out what it was doing from scratch each time I looked at it

#
#               this fires if someone clicks the "+Snippet" button
#
#               we need to insert a new snippet after the current one
#               (if there is a current one) in the current narrative
#               then we need to insert a node into the tree view
#               representing that snippet
#
                button_panel.snippet.Click += def(o,e):
#                      
#                       this should never be called unless we have a current
#                       narrative
#
                        assert narrative_index != -1
#                      
#                       get the narrative object
#
                        n as Narrative = scene.narratives[narrative_index]
#                      
#                       add one to the current item index so it points at
#                       the slot where the new item will be stored
#
                        item_index++
#                      
#                       create the snippet and add it to the narrative list
#
                        sn = n.Add(Snippet("NewSnippet"), item_index)
#                      
#                       insert a node into the treeview for the snippet
#
                        tree_panel.insert(narrative_index, item_index, sn)


That's neat and farily efficient. The trouble is I'm going to need one of these for each narrative item.

#
#               same basic deal, but using thumbnails.
#               it would be nice to factor out the common code here
#
                button_panel.thumbnail.Click += def(o,e):
#
#                       check index, get narrative, bump index
#
                        assert narrative_index != -1
                        n as Narrative = scene.narratives[narrative_index]
                        item_index++
#
#                       add the Thumb object
#
                        th = n.Add(Thumb(), item_index)
#
#                       insert a node
#
                        tree_panel.insert(narrative_index, item_index, thumb)


Now the only difference there is the class being constructed. Oh, and Snippet() takes an argument - but that can be fixed easy enough. Could I pass the type object and instantiate a generalised version?

I keep a lab folder around so I can run experiments for this sort of thing:

def make_obj(typ as System.Type):
        return typ()

class Foo:
        pass

class Bar:
        pass

o1 = make_obj(Foo)
assert o1.GetType() == Foo
o1 = make_obj(Bar)
assert o1.GetType() == Bar
assert o1.GetType() != Foo


After a little thrashing around, that works. Let me see if I can apply it to the problem at hand

No comments: