Methods Should Be Object Safe

submited by
Style Pass
2024-05-10 17:30:07

I think we should use “method”, in Rust, to refer specifically to associated functions which would be object safe if put in a trait.

I was chatting with a friend about object oriented programming and wanted to use Rust to illustrate why I find it odd that programmers often act like “OOP” is one big concept, when, really, it’s more like a kind of Vietnamese spring roll of concepts that can be inserted or taken out depending on preference.

It’s hard to call this “object oriented” in any meaningful way, although I’m sure some readers will enthusiastically correct me (which I welcome!) Counter does not encapsulate its data, nor is its behavior in any way bound to that data.

We can also write associated functions, which are a lot like free functions but are named differently and written inside impl blocks. Since the compiler knows which type the function is “about”, it also gives us a shortcut; instead of naming the type when it’s used in that function, we can just write Self.

Here, Counter still doesn’t encapsulate its data, but its behavior - increment - is bound, at least in name, to Counter as a type. I could define a Cycle::increment in the same module without any confusion occurring. Is this OOP? I say no; we’ve essentially just changed the name of the function, and made it a bit more ergonomic to import.

Leave a Comment