[Tutor] get name of calling class at runtime
Alan Gauld
alan.gauld at btinternet.com
Sat Aug 22 00:58:08 CEST 2009
"Serdar Tumgoren" <zstumgoren at gmail.com> wrote
> I'm trying to create a data-retriever class that executes certain SQL
> statements based on the name of a calling class
This is a really bad "smell" from an OO design point of view.
> can group a bunch of SQL statements in one place; they're currently
> scattered all over the program and it's getting unwieldy).
Normally in an OO program the SQL for each class is in the methods
for that class. That way any changes to the class canbe easily reflected
in the related SQL.
> class DataSources(object):
> def getdata(self, caller):
> if caller == 'CallerA':
> # execute sql for callerA
> elif caller == 'CallerB':
> #execute sql for callerB
This is exactly the kind of code that OO and polymorphism tries to avoid.
It is one of the most error prone and non performant code patterns you
can write.
Why not put the SQL for classA in classA?
> class CallerA(object):
> def getdata(self):
> caller = self.__class__.__name__
> dao = DataSources()
> dao.getdata(caller)
Just put the SQL for A here.
Then if you add new classes you don't need to go and change
your DataSources class as well. Thats what polymorphism is for.
> So I'm wondering, is there any way to have the DataSources class
> access the name of the calling class at runtime, and avoid having to
> pass in the "caller" variable? Perhaps there's some other standard
> approach to this kind of problem?
There are ways of doing what you want, but the "standard" way is
to keep the code for class A in class A. Thats why its called
Object Oriented programming.
HTH,
--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/
More information about the Tutor
mailing list