Friday, August 25, 2023

Function Oriented Code

Not an anti-OOP screed. Just some thoughts.

Maybe we want Object_s_ plural instead of singular. ObjectsOrientedProgramming

Methods are so good. Why should they limited to just one object?

class Rocket:
    def update(self):
        self.x += self.dx
        self.y += self.dy



Maybe we can say

def rockets_update(rockets: [Rocket]):
    for r in rockets:
        r.x += r.dx
        r.y += r.dy

Is that better?




I think it offers some advantages. We can now operate on a list of rockets, not a single rocket.

Is there a computer science quote about counts are either "none, one, or infinity"?

Why a list? 

Because a list can be empty. That means we have Options.

let rockets: Option<Rocket> = None;

or 

rockets: [Rocket] = []

...

Enums:

We love enums, but not in our params. 

Put enum in your objects instead.

Now our methods don't need to be so defensive.

def rockets_update(rockets):
    # defense!
    if not rockets:
    
    return
    # ok, safe to do rocket stuff

Can go back to being

def rockets_update(rockets):
    for rocket in rockets:
        # do rocket stuff

Not having rockets isn't a special case.


The Builder Pattern

Why not return our arguments too?

def rockets_update(rockets: [Rocket]) -> [Rocket]:
    for rocket in rockets:
        # do rocket stuff
    return rockets

Taking and returning a list like this makes writing tests so easy you might enjoy it!

given = [rocket(), rocket(), rocket()]
got = rockets_update(given)
want = [
rocket1, rocket2, rocket3]
assert got == want

Maybe we can turn entire tests into single elements in the list (say rocket2) to test against.

Do people still read these?