Should we separate business logic and ORM mapping classes?

Diez B. Roggisch deets at nospam.web.de
Tue Apr 14 05:41:18 EDT 2009


一首诗 wrote:

> Hi,
> 
> ( First, this is not a question about if we should use ORM.   It's
> question for these who are already using it. )
> 
> Usually, I only use ORM, like sqlalchemy just as an abstraction layer
> of
> database.  So these mapping objects I wrote only contains data but not
> behavior.
> 
> For example, if I have a class User, I would write another class
> UserManager which with a methods like addUser, delUser.  But recently
> I am thinking of moving these methods to User.  That sounds more OO
> style.
> 
> What's your opinion?  What's the benefits and problems of this style?

We do that. Whatever behavior objects have that involves modifying or
creating other entities is put into the objects themselves. Of course
within reasonable limits.

OTOH what we don't want in there are methods targeted at e.g. rendering the
objects as HTML. For example, if a user-object has a mandatory email, but
an optional name you want to display the name if it's there, otherwise the
email.

We use a generic function, view (abbreviated v) available in our templates
to allow for this:

v(user).display_name

will work by decorating the user-object, delegating unknown calls to the
user itself. The UserDecorator looks like this:

class UserDecorator(Decorator):

   def __init__(self, user):
       self._delegate = user


   def __getattr__(self, name):
       return getattr(self._delegate, name)

   @property
   def display_name(self):
       u = self._delegate
       return u.name if u.name else u.email


Diez



More information about the Python-list mailing list