These are a few of the rules I try to follow in my design. So far, they’ve helped me out.
I aim to finish all interaction with the database before I get to the template layer.
This is non-trivial because it is so easy to forget that a method or an attribute will evaluate into a query. I use this rule because it lets me be certain about the number of interactions each page will have with the database.
I avoid branching (if-else clause) in my templates as much as possible.
I have a really hard time detangling code when I find a bunch of nested if statements. For all but the most trivial instances, I prefer to have a bunch of similar templates and then choose the best one. For example, instead of handling both a successful login and a failed login in a single template, I’ll make two different files and then choose the right one in my controller.
In practice, I have some really similar templates. But then I go back and strip out as much of the common code as possible and put those into widgets.
Any time I find a select() call in my controller, I consider making a new method in my model.
When I write something like this in a controller:
bluebirds = model.Bird.select(Bird.q.color == 'blue')
I usually come back later and put in something like this into the Bird class:
class Bird(SQLObject):
color = UnicodeCol()
@classmethod
def by_color(cls, color)
return cls.select(cls.q.color == color)
Now I have something that I can reuse. If I’m feeling whimsical I’ll use functools.partial to do something like this:
class Bird(SQLObject):
color = UnicodeCol()
def by_color(self, color):
return self.select(self.q.color == color)
redbirds = classmethod(partial(by_color, color='red'))
bluebirds = classmethod(partial(by_color, color='blue'))
Sidenote: I couldn’t figure out how to use the @classmethod decorator in the second version of by_color because partial complained. Appararently, callable(some_class_method) returns False, and partial requires the first argument to be a callable.
Maybe a reader can explain to me what’s going on there…
Add New Comment
Thanks. Your comment is awaiting approval by a moderator.
Do you already have an account? Log in and claim this comment.
Add New Comment