I am developing a simple webserver which handles the communication with the browser via XML.
In order to ensure that the type of the variables is correct, I wrap (most) of the attributes in my classes via getters/setters. Something like:
class Animal(object):
def __init__(self):
super(Animal, self).__init__()
self.age = None
def setAge(self, age):
try:
self._age = int(age)
except TypeError:
self._age = None
def getAge(self):
return self._age
age = property(getAge, setAge)
The server also has an authentication and permissioning system (the typical login/password thingy...).
Let's say the logged user doesn't have permission to set the Animals' age in the server, but he's trying to (a bit of a huacker, we've got here, because the javascript should have disabled the 'age' input text but that's a different issue)... Back to the point!:
Right now, when I receive a POST, I open the XML contained in it, and check if someone is trying to set something he doesn't have permission to. Something like:
def receivePOST(request):
xmlTree = Utilities.getXMLTree(request.body)
loggedUser = Utilities.getLoggedUser()
if xmlTree.findtext("age") and not loggedUser.hasPermission("setAge"):
raise Exception("User %s was trying to change the age!!" % loggedUser.userName)
(of course, in the "real" server there are way more if...elif... because there are way more permissions to check)
I was wondering if it's a good idea to put do that permission checking in the getters/setters (well... in the setter, mainly). It would have to be something like this:
class Animal(object):
def __init__(self):
super(Animal, self).__init__()
self.age = None
def setAge(self, age):
if age is not None:
loggedUser = Utilities.getLoggedUser()
if loggedUser.hasPermission("setAge"):
try:
self._age = int(age)
except TypeError:
self._age = None
else:
raise Exception("User %s was trying to change the age!!" % loggedUser.userName)
else:
self._age = None
On one hand, it seems a pretty natural place to check the permission when you're actually going to do something. That would also 'shield' all the classes in my server in a much more effective way (what if somehow the 'age' is being set without going through the 'receivePOST' method?... There wouldn't be a permission check in that case). On the other hand, that means that I can only use my Animal class in the server enviroment (where I have a 'loggedUser').
Also, I've read that properties should (ideally) be kept simple, and that is not a great practice start loading the getters/setters with code that can cause a lot of side effects (some people say that is difficult to track errors when the code just reads: myDuck.age = 512)
I don't know... What do you think?
Thank you!
Related:
When and how to use the builtin function property() in python
Python @property versus method performance - which one to use?