Stop Writing Classes

Type:
Talk
Audience level:
Intermediate
Category:
Best Practices/Patterns
March 9th 12:10 p.m. – 12:40 p.m.

Description

Classes are great but they are also overused. This talk will describe examples of class overuse taken from real world code and refactor the unnecessary classes, exceptions, and modules out of them.

Abstract

Classes must be nouns but not every noun must be a class. If your class only has two methods and one of them is init you probably meant to write a function.

MuffinMail recently refactored their API; it went from 20 classes scattered in 22 modules down to 1 class just 15 lines long. It was a welcome change, but we'll further refactor that down to a single function 3 lines long.

The Python stdlib is an example of a namespace that is relatively flat. You won't find packages that consist of a single module defining an exception, and you won't find many exceptions at all - just 165 kinds in 200k lines of code. That's a tiny ratio compared to most projects including Django.

Of course there are things, like containers, that should be classes. As a final example we'll add a Heap type to the heapq module (admit it, you already have one in your utils.py).