Chris Padilla/Blog

My passion project! Posts spanning music, art, software, books, and more
You can follow by RSS! (What's RSS?) Full archive here.

    Functional vs. Object Oriented Programming

    I've been between projects in Python, Java, and JavaScript. Aside from the syntax differences, I've been pausing to wonder why the context switch takes time.

    The answer has to do largely with the programming paradigm these languages tackle programming challenges.

    There's a spectrum here between Functional Programming and Object Oriented Programming. While all three can manage both paradigms in this day and age, their communities favor being on different poiints along the spectrum:

    • JavaScript leaning heavily towards functional programming
    • Java towards Object Oriented Programming
    • Python sitting in the middle with great support for both paradigms

    If you've started in web development, more than likely functional programming is very familiar. So here I'll explore how to make the switch in thinking in an OOP way coming from that perspective.

    Functional Programming

    At the risk of stating the obvious: FP is built around functions. These individual functions are not tied to an object. They take inputs, process those inputs, and return a result.

    
    const add_then_multiply = (a, b, c) => {
        let res = a;
        res += b;
        res *= c;
        return res;
    }

    What my silly example demonstrates is how a function takes in a handful of arguments, calculates through them, and returns the result. Side effects are possible, but not desirable. This paradigm fits nicely with unit testing and TDD because it's simple to test. If I put in 1, 2, 3, I expect to get 9.

    JavaScript takes this a step further by treating functions as first class citizens. A function can be passed into another function (referred to as a callback) and then call that function within its own procedural process.

    To oversimplify the pros — we are namely looking at a process that thrives on specific calculations and processes. This can lend short programs to be easy to read and unambiguous. When avoiding side effects, there's no confusion around what the program is doing.

    Switching to Object Oriented Programming

    Functions exist in OOP, but the major difference is that they are tied to data. I'll sum up my case right here: If you're looking to switch your thinking between the two, start thinking about how groups of data need to operate and can interact with each other. This is different from thinking of only the functionality that needs to occur.

    In Python, say that I have a representation of a web page. I want to encapsulate the data and some functionality around it in a class:

    
    class WebPage():
        def __init__(url: str, name: str):
            self.url = url
            self.name = name
            self.visits = 0
            
        def visit_url(self):
            # Open url
            
        def print_webpage_details(self):
            print(f'{self.name} at {self.url}')
            
        def add_visit(self):
            self.visits += 1

    This simple example demonstrates the shift. Not only have I defined some functionality, but that functionality is primarily centered around manipulating and using the data that's present on the instance.

    Imagine it multiplied by dozens of classes then. All with their own state and functionality.

    In fact, if you've been writing React, you've likely already been thinking in a moderately OOP way! The execution is largely functional. Hooks are primarily event driven. But it's the encapsulation with state and methods that also blends a bit of OOP into the way React is written.

    There's more complexity that can naturally be held this way. And the power comes from having some flexibility to employ both. A procedural script employing functional programming that leans on Objects to encapsulate large amounts of data and complexity is what most apps realistically employ. So it's not a matter of one or the other, but understanding what problem you're trying to solve and picking the right paradigm for the job.


    Lucy Knows We'll Be Together Again...

    Listen on Youtube

    My pup and I missed each other while I was in Chicago this week!


    Turquoise Sky

    🌙

    🌘 🦊


    Cussedness in Art

    It's one thing to do work in spite of nay-sayers and critics. It's another, greater challenge to continue on in a direction different from where the admirers and allure of "success" draws you.

    Tim Kreider exploring the stubborn nature of painters De Chirico and Derain:

    What I can’t help but admire about them is their indifference to critics and admirers alike, their untouchable self-assurance in their own idiosyncratic instincts and judgment. I admire their doggedly following their own paths, even if I’m not as interested in where they led. I admire their cussedness. It’s a value-neutral quality in itself, cussedness, amoral and inæsthetic, and not one you can really emulate, anyway—it would be like trying to imitate originality. But such artists’ careers demonstrate that it is at least possible to move through this world unswerved by its capricious granting or withholding of approval. They’re examples, good or bad, to their fellow artists as we all feel our blind, groping way forward—or, sometimes, back—through the dark of creation.

    Kreider's closing metaphor on moving through "The dark of creation" is something that the richest creation requires returning to time and time again.

    (Found while digging deeper on the always fantastic weekly newsletter by Austin Kleon, this week on writing.)


    Application Monitoring with Open Telemetry

    I've been spending time diving into instrumenting our serverless apps with Open Telemetry.

    The situation: We've previously used a custom logging solution to monitor a few cron jobs. It's worked well for a time. As we scale, though, we've started looking for another solution.

    An issue with most off-the-shelf monitoring services is the amount of vendor lock in you set yourself up for. Thus, the Open Telemetry protocol came about.

    The gist is that it's a standardized way your application can emit:

    • Traces: Path of a request through your app. Think multiple lambda functions. Broken up into individual spans
    • Metrics: Measurement captured at runtime. Anything you'd like to quantify.
    • Logs: What you emit from your logger. Can be tied to a trace.

    These data points are then sent from the application to a collector that can send these to your backend of choice. Many vendors have supporting libraries, including big players like Data Dog and New Relic.

    Concepts

    There are a few concepts to understand before getting started. You'll likely be setting up several services to instrument your application.

    The pieces are:

    • Instrumented App: Your code wrapped in an SDK to create traces, metrics, and logs.
    • Exporter: Responsible for sending your data to the collector. Can exist within your application.
    • Collector: Can receive and send Open Telemetry data. This is where you will point your application to.
    • Back End: Your vendor or self hosted solution specific service for storing and rendering your data.

    Instrumenting The App

    The fastest way to get started is with a zero code instrumentation. There are slick ways for the Open Telemetry (OTel) SDK's to integrate with a web server like Flask.

    For an application without a framework, though, there's a bit of manual work to do:

    The official OTel docs outline the packages to import. You'll have to choose between gRPC or http protocol as your means of exporting. (Though, it seems the gRPC implementation is mostly a dressed up HTTPS protocol.)

    Once you have it setup, emitting traces is straightforward:

    with tracer.start_as_current_span(fn.__name__, links=links) as span:
        span.add_event(f"{fn.__name__}() started")
        
        # Do work
            
        span.add_event(f"{fn.__name__}() complete")
        return result

    Setting Up the Collector

    You could point your OTel config directly to your backend. Much of the benefit, though comes from using this in a distributed system. Here, a dedicated collector comes in handy.

    If you're in an AWS environment, you can take advantage of the AWS Open Telemetry Collector. Setup here is primarily a bit of configuration.

    My OTel project is still a work in progress, so that's all for now! I'll leave the nitty gritty for another post.