As I was reading the book Dreaming in Code, I came to a part that resonated with me. Actually that happened many times, but the time related to this blog entry was when the Chandler team hired a Python expert to look at their code. He scolded the developers for using Java methodologies in Python, thus creating a huge and overly complex code base. I look at how OOP in Python is presented in many books and websites, and I think that the Chandler developers are not the only ones guilty of this.
So in rewriting SURRAnet, I'm trying to break away from some of the mistakes I've copied from examples I've seen in the past. Often classes are treated as functions on steroids or variables with attributes, but I think the true beauty of OOP is deeper than that. In the SURRAnet rewrite, I'm trying to harness the true power of Python OOP by creating the equivalent of custom types.
I've already done this in some places. For example, the "core" SURRAnet database class, SDBM, is basically a simple Python dictionary (dict) with file operations added to it. It's simple yet beautiful. The SchoolYear class is another example of objects that behave like special variable types, allowing me to use those objects in very intuitive and simple ways.
Yesterday I reworked the StudentData class (now just Student) in light of the added flexibility I have since breaking away from Apache. Instead of being a sort of ugly extension of the StudentDB class, it is truly a "student type", and instead of handling student IDs all the time, I can actually just handle Student objects!
This adds many benefits and simplifies much of my code. Let me leave you with this one example. In the past, sorting students by their name was a big pain, since students were represented by integers (their ID), and sorting those integers would not do. If you look at the current code I have available for download (at the time of this writing), you'll see this strange voodoo sort method in the StudentDB class (sort_stuids_by_fieldname or something like that). Now, by overloading the __cmp__ operator of the Student class, I can have lists of Student objects and just call a regular sort() on that list, and poof - sorted students! No funky voodoo! Here's an example:
SDB = database.StudentDB()
students = SDB.students
students.sort()
for student in students: print student.fullname
Needless to say, the code is simple, beautiful, and logical. I'm quite looking forward to using my new student "type" today as I continue to switch SURRAnet over from Apache-based to a stand-alone server program.
0 comments:
Post a Comment