Main Content

Factory methods and SqLite in use in a Python teaching example

Archive - Originally posted on "The Horse's Mouth" - 2010-05-29 22:36:58 - Graham Ellis

I've just uploaded a neat little example - [here] from last week's Python course - it's amazing what you can do in a very few lines of code.

The application scenario is that we have a database of customers - some are residents at our hotel and others are delegates on our courses. Being mercenary folks, our accounting team wants to work out the income for a selection of customers ... and the algorithms are different for residents and delegates, even though many of the properties (a.k.a. attributes) of both groups (a.k.a. subclasses) of customer are handled identically.

Some interesting features of the demo ...

• I have used SqLite as my database engine. For small to medium sized database requirements, SqLite is excellent and growing. It's shipped with modern versions of Python, it's good, and it avoids the need for an extra level of process - a database daemon - that you'll get with MySQL or Oracle. The database can be accessed from "any" language - not just Python - and it transactional across concurrent applications (which other daemonless databases are not).

• As records are read off the database, the may pertain to either customer type - and I have used a static factory method to build my new objects, allowing me to simply pass in the data from the database to a piece of code that's maintained with the classes themselves and have it return a new customer object of the appropriate subtype. There is no need for my main application (and it would not be desirable) to get involved in the detail of working out what type of customer each record pertains to as it comes off the database.