Don't peek at my password

Hopefully I don't accidentally copy-paste any passwords into this article. Here goes...

I wrote a program this afternoon that perfectly demonstrated the benefits of OOP... and thought it'd be fun to share some code.

Because I was writing a script in a very exploratory fashion, using a fairly complex Python library. A library I was COMPLETELY unfamiliar with.

We've all been there.

This script uses the API of an email-delivery service. And happily, they provide a Python SDK:

  1. subscribers = Subscribers.from_file(subscribers_txt)
  2. consumer_key = os.environ['AWEBER_CONSUMER_KEY']
  3. consumer_secret = os.environ['AWEBER_CONSUMER_SECRET']
  4. access_token = os.environ['AWEBER_ACCESS_TOKEN']
  5. token_secret = os.environ['AWEBER_TOKEN_SECRET']
  6. aweber = AWeberAPI(consumer_key, consumer_secret)
  7. account = aweber.get_account(access_token, token_secret)
  8. mlist = account.lists.find(name=self.LIST_NAME)[0]
  9. active_subscribers = {
  10. subscriber for subscriber in mlist.subscribers
  11. if in subscribers.emails
  12. }
  13. for subscriber in active_subscribers:
  14. # ...

Eyes glazed over yet? Well, I sprinkled some OOP pixie dust on it... and turned it into this:

  1. subscribers = Subscribers.from_file(subscribers_txt)
  2. app = App.from_environ()
  3. for subscriber in app.get_active(subscribers):
  4. # ...

13 lines of code, replaced with 3. Tell me, which is more readable? More understandable?


The second one. Hands down.

And what did I do here? Did I remove any complexity?

No. I *hid* it.

That's one of the GREAT MASSIVE FREAKING BENEFITS of object-oriented programming. Code organization. Taking the complexity that has to be there, that just can't be simplified away...

And compartmentalizing it. So you can read parts of the code that use that complexity... but quickly, clearly, and accurately understand what's going on.

I don't care if you're a web developer, a data scientist, a this or a that. Whatever kind of Python code you're writing...

You can upgrade your code, and your happiness, by coding this way.