I recently had the opportunity to speak atDjango Congressin Tokyo on May 19th about lessons learned while building Kwoosh.
Preparing the talk was a good opportunity to reflect on how much Kwoosh has changed in this past year. Sharing some of what we learned was a lot of fun. Real code from old and new Kwoosh are inmy slides.
One of the major lessons I learned and spoke about was avoiding Class Based Views (CBV). Class Based Views are a great idea: remove most of your repeitive code into a common class and mixin only the bits you need. However, each time I’ve tried to rely on only CBV I’ve always ended up with code that was difficult to follow.
Our solution was to completely ditch CBVs and write Kwoosh using regular function views. In my talk I shared our approach to make the migration while allowing us to reuse code. I was surprised after the talk when a number of people came and asked see how we did it.
The basic idea is that we have a regular view and use decorators to wrap our functions with shared functionality. Inside our view we can define a number of functions to handle each method that we wish to support. A view looks something like this:
How is this different from just a CBV with a method for “get” or “post”? First, it’s easy to see exactly how the code executes. You’re not left jumping between 3 different files, documentation, or even diving into the Django source to understand the flow. Second, we can handle multiple get responses from a single endpoint e.g. an admin user gets this response while a regular user gets another. Lastly, we have the freedom to name our functions however we’d like.
The supporting decorators are quite simple and remove a lot of the grunt work from creating and maintaining new views in Kwoosh.
Creating multiple decorators like has allowed us to get the best of both worlds: code reuse and a simple execution path.