OOP in Python, part 19: When do you need OOP?
MP 66: And when do you not need to use OOP?
Note: This post is part of a series about OOP in Python. The posts in this series (except for the first one) will only be available to paid subscribers for the first 6 weeks. After that they will be available to everyone. Thank you to everyone who supports my ongoing work on Mostly Python.
This has been a long series; the next post will be the last one in the series.
Once people start to understand how to use OOP concepts, two important questions come up:
Now that I know how to use classes, how do I know when to use them?
When is it okay to write code that doesn’t involve OOP?
These are great questions. Sometimes people learn how to write classes, and then think everything should be written as a class. A lot of this comes down to experience, but there are some general principles that can help you know when to structure something as a class, and when to use simpler structures such as a collection of functions.
In this post I’ll share an example from my own work where I chose specifically not to use OOP, and one where I decided to reimplement non-OOP code using a class-based structure.
Simple procedural scripts don’t need OOP
A procedural script is one that proceeds from one instruction to the next, with little or no redirection to other parts of the script. Many small scripts that we write are procedural in nature.
Substack hosts weekly Office Hours for writers, and I like to participate sometimes. It often takes place in a single comment thread, and the comments stack up quickly. It’s one of those online events where showing up as soon as it starts is really helpful. The problem though, is that it doesn’t start at a consistent time.
To address this, I wrote a script that polls the Office Hours page once a minute for up to 90 minutes, and opens the page when a new session is posted. Here’s the entire script:
Keep reading with a 7-day free trial
Subscribe to Mostly Python to keep reading this post and get 7 days of free access to the full post archives.