User or UserManager ? Problems of Observer Pattern

Michele Simionato michele.simionato at gmail.com
Sat Apr 4 01:14:38 EDT 2009


On Apr 3, 7:34 pm, 一首诗 <newpt... at gmail.com> wrote:
> #----------------
> # Choice 2
> #----------------
>
> class UserManager:
>
>     users = []
>
>     @classmethod
>     def delUser(cls, user):
>         cls.users.remove(user)
>
>         RoleManager.onUserDel(user)
>
> class RoleManager:
>
>     roles = []
>
>     @classmethod
>     def onUserDel(cls, user):
>         for r in cls.roles.items():
>             r.users.remove(user)

Choice #2 is better, but it should not be implemented
this way. Using a class as a pure container of methods,
a big singleton, makes little sense, since you would
be better off with a module and old fashioned procedural
programming. You recognize this and are worried about this.
You do not need to be worried to much,
since there is nothing wrong with procedural design
(but you should use modules not classes). If you want
to be more object oriented, the first thing is to understand
is that you define objects in order to pass them to
other objects. For instance, you are using a global
list of users as a class attribute, but I would
just pass the list in the __init__ method, and
make it an instance attribute. I also would make
a RoleManager instance and pass it to the UserManager,
so that it can be used directly. Or perhaps I would
define a single UserRoleManager doing all the job.
It depends.
But all the point of OOP is to pass objects to other objects.
It is not bad to think of a data object as of a record
on steroids. Objects which are purely data and not
behavior are the simplest and the best objects, start
from them.
There are also objects which are mostly behavior
and nearly no data (the Manager objects here, which
just act over collections of other objects). Those
are more difficult to write. OTOH, nobody forces you
to write the managers as objects. You may find easier
to write a set of manager functions. This set of
functions can later become methods of a Manager object,
if it seems fit, but that must be done a posteriori,
not a priori.
Perhaps you should read some book like "Programming Python"
by Ludz which has many examples of how to write OO applications
in Python (I mean no offense, but indeed from you examples
is seems to me that you are missing the point of OOP,
as you are the first to recognize).
HTH,

               Michele Simionato



More information about the Python-list mailing list