The Care and Feeding of Objects: Equality Matters

| Comments

It’s tempting to write classes with a handful of attributes and declare the code “Object Oriented”. Sadly, cranking out data transfer objects isn’t object-oriented design.

Instead of one uber-post with tons of thoughts around all the extra stuff good OO demands, I’m tackling one thing at a time and writing a series of posts on the topic. This first one deals with object equality.

Equality Matters

Even if you’re making a rinky-dink class, think hard about overloading the equality operator.

For example, given a Person class:

class Person:
    ssn
    first_name
    last_name
    favorite_color
What does it mean for two Person instances to be equal? Does every attribute have to match? What if everything but favorite_color is the same?

These kinds of questions are important for building an accurate model. It seems reasonable to say that SSN is the deciding factor for equality:

class Person:
    ssn
    first_name
    last_name
    favorite_color

    def __eq__(self, other):
        return other.ssn == self.ssn
 

If a web form is used to create a Person and our app checks this against a list of Person’s from the database, it’s easy (and feels good) to write:


form = {'firstname':flavio,
            'lastname':fabrizzio,
            'soc_sec_num': 2223339999}

def check_user():
    people_i_know = database.get_friends()
    user = Person(ssn=form.soc_sec_num,
                           firstname=form.firstname,
                           lastname=form.lastname)

    if user in people_i_know:
        print "Welcome! I know you!"
    
Though == didn’t appear in the above function, it still gets invoked when in tests for membership in the list (look ma, no looping over objects!). We also didn’t need “favorite color” as an input, since it’s not a factor in equality.

If we don’t overload equality, we need to add favorite_color to the form or write logic to see if the input was “equal enough” to what we got from the database. It’s way easier to define it once in the class itself and take advantage of all the sweet things equality gives you for free.

If you love your classes, show them that love. Give them the gift of equality.

Stay tuned for the next installment of the Care and Feeding of Objects series…

[photo courtesy of bayerNYC]

blog comments powered by Disqus