Design Patterns

Go Overboard on Features

I realize I'm treading on dangerous waters with the title of this weeks post, but I'm tired of hearing about "Architecture Astronauts" and "Creeping Featurism" in response to questions I ask developers about specific features. First and foremost, program architecture is something that you should think about before you start coding! The reality is that, even if you don't formalize this step, the act of coding is based on your current mental framework of the problem at hand and your previous experience with software.

The Power of Portlets

I've been an advocate, user and sometimes promoter of the Plone CMS (an extensible content management system built on the Zope application server, using the Python scripting language) for quite some time. For me, Plone's most important feature is the ability to create Plone "products", which plug into the CMS. This allows the creation of a web portal that provides standard HTML CMS functions out-of-the-box, but can be extended to include almost any imaginable application. There's also a great versioning system built into Plone products that allows a CMS administrator to update a product right from the user interface. It also doesn't hurt that I chose Python as my main scripting language (sorry Ruby users/lovers/zealots, but Ruby was my dogs name ... I didn't want to get the two confused. Just kidding! I like Python's consistent and minimalistic syntax. Unlike PERL, there's generally only one right way to do it).

With many sites already running on Plone, I still haven't been able to justify using it for any major web application development projects. For these, we need industrial strength scalability, a more structured language and the support of a mature application server. Combined with the availability of a large pool of expert developers, Java and J2EE has always made the most sense. The problem with selecting Java for these projects was the lack of a framework that allowed the easy, modular development of the application. The adoption of JSR-168 Portlets by the Java community and its implementation by several major application server vendors has finally created an environment that promotes modular components on a Java driven web application.

Python Flyweights

I mentioned at the end of my post on Python Equality that another way to solve the example given was to use the flyweight pattern. I gave code for playing cards that would end up with many small duplicate objects in memory, and that memory usage can be reduced if (as in the example) the objects don't have extra state that wasn't used for testing equality.

Let's look at the final version of the Card class and its usage again:

values = ('2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A')
suits = ('h', 'c', 'd', 's')
class Card:
    def __init__(self, value, suit):
        self.value, self.suit = value, suit

    def __repr__(self):
        return "<Card: %s%s>" % (self.value, self.card)

    def __eq__(self, card):
        return self.value == card.value and self.suit == card.suit

    def __ne__(self, card):
       return not self.__eq__(card)

>>> c1 = Card('J', 'h')
>>> c2 = Card('J', 'h')
>>> c1 == c2
>>> id(c1), id(c2)
(-1210559028, -1210558804)

As designed in the previous blog post, two different objects (as seen by their different ids) equate because of the custom __eq__() handler.

But this is a bit silly -- Cards are so small and simple, having identical objects is wasteful. If we're writing the code for a casino, we don't really want several thousand Jacks of Hearts, we want many references to one object. The idea is that instantiating a Card object checks a hidden pool of objects for a duplicate and returns it, creating a new object only if needed. (Code based on that of Duncan Booth.)

import weakref

class Card(object):
    _CardPool = weakref.WeakValueDictionary()

    def __new__(cls, value, suit):
        obj = Card._CardPool.get(value + suit, None)
        if not obj:
            obj = object.__new__(cls)
            Card._CardPool[value + suit] = obj
            obj.value, obj.suit = value, suit

        return obj

Notice that this uses new-style classes. (Side note: I cringe at anything named "new", "next", "updated", etc. because they tell me nothing. If the only thing you can say about a reimplementation is that it's not the old one, put down your copy of Refactoring and back away from the computer. Take up writing toothpaste advertisements.) If you're wondering what's up with __new__, Guido explains the difference best:

__new__ is the first step in instance construction, invoked before __init__. The __new__ method is called with the class as its first argument; its responsibility is to return a new instance of that class. Compare this to __init__: __init__ is called with an instance as its first argument, and it doesn't return anything; its responsibility is to initialize the instance.

The other possibly-unfamiliar element is the WeakValueDictionary. In a nutshell, it's a dictionary that deletes its entries if no other variables point to them. When instantiating a Card object, it checks in the Card class's _CardPool to return an existing object, or creates a new Card object if needed.

If you're confused, take a few minutes to play with the code. Insert print statements into __new__ to show you the contents of _CardPool.items() and whether a new object is created. There's a lot of important object orientation concepts at work in a short block of code: inheritance, the difference between classes and objects, references, and overriding.

I've removed the __eq__ and __ne__ calls because two Cards with the same value and suit are the same objects, saving our casino many gigs of precious RAM:

Learning Design Patterns – Iterator Pattern

This week I'll be stepping through the Iterator Pattern in my series on design patterns plucked from this book and from examples on the Internet.

What is it?
The Iterator Pattern encapsulates the functionality for stepping through a collection of items. The iterator object implements the stepping; the aggregate itself does not step through its own collection.

The pattern generally has a few of methods like first(), hasNext(), Next(), isDone() in some combination. In some programming languages it is possible to step through an iterator using a For Each item in Aggregate....<code>....Next type of construct.

Where is it used?
Anywhere there is a group of items. An array list is a common example; an iterator would step through the array items until the end of the collection was reached.

New Contributor - Peter Harkins

Let's all give a warm welcome to our newest contributor, the incredibly brilliant and good-looking Peter Harkins.

That's right, clap for me -- er, him, clap for him. I'm not writing this about myself. I mean he's not. Crap.

Hi, folks. I'm a new contributor to CodeSnipers. I'll be writing mostly about design and coding, though I may wander into MicroISV territory if any of my side projects should start doing particularly well.

To tell you a little about myself, I'm a 25-year old web developer in Chicago, IL, USA, Earth. I've been programming for about fourteen years, professionally for the last 5.5. My constant obsession is writing code that's just a little bit better, a little bit smarter, a little bit higher-level. Even though the steps I've taken and will be writing about are small, they're a great way to improve code and design every time you touch it.

Learning Design Patterns – Template Method Pattern

This week I'll be examining the Template Method Pattern in my series on design patterns plucked from this book and from examples on the Internet.

What is it?
The Template Method Pattern lays out the steps in a process (algorithm) and allows subclasses to handle one or more of the steps internally. The pattern has a method that just contains a list of method calls to complete the process (create something, package it, sort it, deliver) that can not be overriden or augmented. Some of the process methods may be handled by the pattern (create something and deliver), while it makes the subclasses handle the others (sort it, package it).

Stupidly Easy MVC - Group Membership Application - Part 2

This is part two of an example of using my Stupid Easy MVC framework in PHP. In this example we will talk about the how to use the Model. Originally I thought I might make the Directory a separate controller, but at this point I decided not to. I have some more ideas that I haven't quite worked out yet for extending this even to be more like the Rails framework for Ruby (again I do not expect to totally implement RoR, spare the language wars please!).

Stupidly Easy App Walkthough

One day, the phone rings.
Joe: Hey!! can you make a website for my Candy Wrapper Club?
You: "Candy Wrapper Club?!?"
Joe: "Yes! We collect Candy Wrappers! We just need a little bit about the group, how to contact us and a membership list. It will probably only take you a week. My cousin has a webserver with PHP and MySQL. How about it?
You: <sigh> Sureeeeeeee, I've been wanting to try this MVC thing with PHP.
This is a long one, so grab a cup of coffee!

Learning Design Patterns – Facade Pattern

This week I'll be simplifying my life with the Facade Pattern in my series on design patterns plucked from this book and from examples on the Internet.

What is it?
The Facade Pattern simplifies a complex interface so that it's client can rely on simple methods in the facade that handle multi-step calls to subclasses. The client might call facade.PowerUp, then the facade would turn on all of the subcomponents in the correct order and adjust their initial properties.

Stupidly Easy MVC - Directory Structure

There are probably many ways to setup a structure using MVC and this article will talk about two of the ways I have done it and explain why I did it that way and how I think it works out after the fact.

Structure 1
For this project, I used Ruby On Rails as inspiration (Imitation is the best form of flattery, yes?) and used a separate directory for each of the Model, View and Controller. I knew I I was going to have multiple models as well. I used inline php/html for the view for this project since it was only a few forms and we didn't want to do a template system yet. It would be easy to change to templates later of course by just editing the view methods to call a template instead of spitting out html.