by trashburger · 3y ago · 0 comments
Object programming doesn't mean "inheritance trees", that's just the (IMHO overly simplified) flavor of object programming that we call "OOP". (I'm omitting a full rant from here, which I ought to put on an article at some point.) Object programming is all about state and behavior, just like functional programming; it only differs in how it lays out the behavior namespace (object programming uses inheritance of behavior through lookup chains, which puts the object in focus; functional programming inverts that and uses the structure of the object to dispatch, putting the function in focus).
Grouping behavior together in a single function like the article suggests is, IMO, an anti-pattern and one that I consider to be one of the great disadvantages of a functional programming style. Bundling behavior together means the behavior is out of the control of the object; the object's identity now becomes a critical part of the operation being performed. IMO, putting the focus on behavior is the wrong approach here.
Don't get me wrong, I'm all for some features in functional programming; immutability is great for being able to make assumptions about program state and re-entrancy, for example. But I think the tendency to "lock" behavior into functions and not letting objects define their own behavior is a major shortcoming.
Lets say you have a Player object who has an Inventory (can also be an object) and an inventory contains items like Swords and Bows etc. When a player wielding a sword takes a swing at an enemy, a particular animation has to play, and sword swing and sword hit sound effect has to play.
Which object contains the code that performs the rendering of the animation? Is there an "Animation" object that contains it? Does it call some setPosition/setRotation object in the sword and the player? Does the Animation object know how to call the appropriate Metal/Direct3D/Vulkan APIs or is that another object?
Or is the right solution to have an animation subsystem that doesn't care at all about "players" or "swords" and is only concerned with mesh data and how to transform it? Answer: the latter, which is what every game engine that wants to be even remotely efficient does.
That's not to say the Smalltalk idea of building larger systems out of smaller systems communicating via message passing is bad or anything, the problem is the OO idea of tying data to behavior. There isn't a single OO codebase out there without POD objects.
Data is just objects that don't happen to have any behavior.
You can look at it as there being a continuum between data and behavior:
* Purely just storing raw uninterpreted bits in memory and letting anything read and poke at them.
* Storing raw data in memory but having an API that ensures that the data is in a valid state and maintains invariants.
* Encapsulating data behind an API that gives you flexibility to change the representation without breaking users.
* Attaching additional behavior that happens to use that data directly to the type that stores the data.
Object-oriented languages support the full continuum, but the language itself certainly doesn't require you to go all the way for every type. Different kinds of data and different domains will naturally fit certain points on this continuum.
When you say, "There isn't a single OO codebase out there without POD objects", I consider that a feature of object-oriented languages: They are flexible enough to model a range of state/behavior policies.
Often data only needs to be read so new data can be produced. There’s no need for encapsulation here. If you want to ensure that you’re dealing with data that has certain properties then you can do that with types, schemas or simply read it.
Encapsulation at a lower level is needed when you mutate state or otherwise own resources and possibly multiple things need to be updated in tandem. In this case you want operational semantics and not look at the innards of the data. So the interface you want describes behavior.
And then there is another level where you only care about coordination of messages. The interface is not the data/state behind whoever produces or reads them. You don’t even care about behavior anymore.
Objects are a pattern that appears in all languages (if you are implementing a plugin API of any sort you need to have hidden data and a shared interface). A language having OO features only makes this easier. Same with FP, you can do OO and FP in C, all FP means is that your functions don't have hidden side effects.
If you make a Point class with getters and setters for its internal data, you've just emulated a record type in a really dumb and inefficient way. The whole "you could replace the internal representation with polar coordinates" example never ever happens.
Historically, Simula-67 replaced records (in competing derivatives of Algol 60) with classes, precisely because it was clear to the designers that an object is a fundamentally different thing.
And yes, of course nobody actually does this kind of thing with Point. The whole Java-style getX/setY business was never what OO is about. A well-designed OO language shouldn't make you encapsulate data until the moment you actually need non-record-like behavior.
As for your specific example, you don't have to add the behavior of actually playing the sound or animating to your `sword` or `player`; I never suggested that the objects themselves having to perform effects being an inherent part of object programming. Maybe you can send `player wieldedWeapon attackSprite` (or `attackMesh`, I'm fond of 2D platformers better :) and then the scene can ask the animation to render itself, same with `player target hurtSound` and `player wieldedWeapon attackSound` and then the sound object can be asked to play itself with a given `audioContext`. Here, we're being as declarative as can be and still giving the objects the freedom to behave however they want within the bounds of the contract they adhere to.
So an object programming style does not, in fact, preclude you from making "POD objects"; it only says that the behavior of an object should be exposed through the object itself, rather than reflectively deciding on what the object should do from the outside.
- The check that the "enemy" is even a valid target (who decides that? The player? What if certain enemies are immune to slashing attacks? The sword then? What about the enemy making the decision? What if it depends on the armor the enemy is wearing, does the armor decide?)
- The calculation of the position of where the sword impacted the enemy (who calculates that? it depends on the animation calculation results, the size and shape of the sword and of the enemy, etc.)
- The sound that plays depends on the type of equipment the enemy has (leather armor vs steel armor) and on the weapon of the player (a sword or a hammer would have different sounds).
- The actual playback of the sound depends on all of the decisions above (the animation, the collision, the materials involved in the collision).
At no point, in any of this, are there messages between these objects. The entities that have to make these calculations depend on multiple data sources, none of which belong to them, that is, the behavior is not associated with the data.
An animation doesn't render itself (rendering requires a rendering context, mesh data, texture data, shaders, etc., who owns them?). A sound doesn't play itself. Collisions don't calculate themselves.
Inert objects don't inherit behavior because they have no behavior, systems do. And systems are effectively "manager" objects (AnimationManager, AudioManager, CollisionManager, etc.), widely considered a bad practice in OO circles.
Systems should indeed support behavior inheritance (I might want multiple different implementations of an AudioManager for different targets or with/without surround sound support, etc.) and since their internal data is hidden (i.e. operating system resources), they are very much objects and working with them is OO programming.
But the rest of the system is not OO, it's very much plain old data being computed upon by plain old functions, and that has nothing to do with OO nor does it need any kind of inheritance.
Even in Smalltalk you see this issue happening. Ints and Doubles respond to messages to implement arithmetic, but for example reading an integer from a stream is a method of the Number class that takes an integer radix and a Stream as input. Why is it not a method of the integer radix or of the stream? Why can't different streams decide how to parse themselves into integers? Because the whole concept of associating behavior here is silly. readFrom is a function.
What you’re describing are great examples of data oriented or relational problems.
In these cases you really don’t think (or can’t) in terms of objects and interfaces, but in terms of relational (or equivalent) data that you see, combine and manipulate from a bird’s eye perspective.
You don’t just care about the individual pieces and their integrity. Your focus are their relationships, which you build on demand.
> No, I disagree, because the right behavior is not determined by a single object but by a combination of factors
Sure, and you can ask one or more of the objects involved about all of those factors!
> The check that the "enemy" is even a valid target (who decides that? The player? What if certain enemies are immune to slashing attacks? The sword then? What about the enemy making the decision? What if it depends on the armor the enemy is wearing, does the armor decide?)
Answer: All of them! Let's walk through it step-by-step:
- The player wants to attack the entity it's pointing at: `aPlayer attackEntityCurrentlyPointedAtIn: world.`
- In order to do this, the player asks the world what it's pointing at first: `entity: world entityPointedAtBy: self.` If nothing is returned, then the player would simply play the shoot animation of the wielded weapon.
- If an entity is returned, the player asks the enemy to be attacked by itself: `entity getAttackedBy: self`.
- The enemy checks whether it's the right kind of entity first (attacking a prop might do nothing, for instance). Afterwards, it asks the source entity about the various factors you talked about (what kind of attack the source's currently wielded weapon would produce, what the armor is, etc.) and responds whether it could be attacked and how much damage was produced. Maybe the enemy could even deal damage back! `source dealDamage: 123 Source: damageSources reflection.`
> The calculation of the position of where the sword impacted the enemy (who calculates that? it depends on the animation calculation results, the size and shape of the sword and of the enemy, etc.)
We already would need the animation context in order to make sense of the animation that would be produced by the attack at this point, so we can just thread it through our messages and ask where on the target entity the strike would happen. Because we would be asking the wielded weapon about the details of what kind of animation it would produce, it can add in any details and modifiers you'd like.
> The sound that plays depends on the type of equipment the enemy has (leather armor vs steel armor) and on the weapon of the player (a sword or a hammer would have different sounds).
> The actual playback of the sound depends on all of the decisions above (the animation, the collision, the materials involved in the collision).
Let's just ask the attack source about what kind of material it is, and then what it would produce if it hit us, and then ask the sound to play:
weaponMaterial: source wieldedWeapon material.
"Assuming you need this level of detail"
ownMaterialAtStrikePoint: strikeSurface material.
weaponMaterial soundForStrikingAgainst: ownMaterialAtStrikePoint
; play: audioContext.
> At no point, in any of this, are there messages between these objects.I think I was able to prove this wrong. ;)
> The entities that have to make these calculations depend on multiple data sources, none of which belong to them, that is, the behavior is not associated with the data.
This isn't how the real world works though. Every action has a fundamental source and a target. Being able to model how different things interact in our system in such a natural manner like message passing can make everything so much clearer.
> An animation doesn't render itself (rendering requires a rendering context, mesh data, texture data, shaders, etc., who owns them?). A sound doesn't play itself. Collisions don't calculate themselves.
But they do! They are the best at rendering, playing and calculating themselves, because they're the information expert: they hold all the details. The code that sends the `play:` message need not know anything about whether the sound is a waveform or Opus; it need not know whether the sound object is actually a `pitchChange` object that modifies the original sound effect. All it needs to know is that the object can be `play:`ed.
> Inert objects don't inherit behavior because they have no behavior, systems do.
A system is simply a hierarchy of objects, as I detailed above, so they absolutely can have behavior.
> Even in Smalltalk you see this issue happening. Ints and Doubles respond to messages to implement arithmetic, but for example reading an integer from a stream is a method of the Number class that takes an integer radix and a Stream as input. Why is it not a method of the integer radix or of the stream? Why can't different streams decide how to parse themselves into integers? Because the whole concept of associating behavior here is silly.
Actually, it makes much more sense than a `stream readInt` ever could. Why does a stream know how to read an integer? Why does it need to know how an integer looks, and how to create one? It is much more natural to ask an integer to take in a stream and create its own representation, IMO.
If the hierarchy is open, the behavior is defined in each subtypes and it's easy to add a new subtypes but you can not add a new operation (a new method). That's the OOP way.
If the hierarchy is closed, the behavior is defined in each function, it's easy to add a new operation (new function) but you can not add a new subtype. That's the ADT way.
This is known as the https://en.wikipedia.org/wiki/Expression_problem
For example, if your application receive JSON objects, you know all of them so, it's a closed hierarchy.
> But I think the tendency to "lock" behavior into functions and not letting objects define their own behavior is a major shortcoming.
"Locking behaviour" happens when you bundle objects & functions together.
For instance, an OOP programmer might create a binary tree, mark the fields as private, and expose a public visit() method.
If you take away the "objects defining their own behaviour", then you're left with just the binary tree. Then different callers can write their own visit() functions.
Essentially visibility is a contract, and sometimes you want or need to go beyond. The language should allow this IMO but make it clear that you are bypassing the contract of the original author.
Making things unreachable is just a PITA for no good reason.
Like this:
type obj1 = { ... }
type sum = | One of obj1 | Two of obj2 ...
match param with | One obj -> f(obj) | Two obj -> f2(obj)
----
There is also the handle pattern which I've used with some success. You basically place some functions in a record/tuple and then call those functions when you need to.
https://jaspervdj.be/posts/2018-03-08-handle-pattern.html
Edit: I mean to say that I've used something similar to the handle pattern in an immutable context (having a central function that takes objects that can be arbitrarily nested which carry their own function and data, and the parent object can call its function on a child object, and the child can call its function on its child, and so on...). Hopefully I am making sense.
Why? Do you have an example to better explain?
If find people rarely talk about the evaluation criteria for which approach to programming is better. That is, what are you optimizing for?
> That is, what are you optimizing for?
I'm optimizing for other programmers to easily be able to see how objects fit together and behave, and for them to be able to easily extend the system without touching the behavior of other components (which you cannot do if you bundle behavior together). I've slowly shifted towards this approach throughout the last few years of my programming journey.
> Do you have an example to better explain?
Let me make an attempt to do so. Let's say that you have an HTML form builder in code (this is something I'm currently working on, if you can't tell ;). Your form builder lets you design the form such that you can split the form into sections, rows and columns. You might design a registration form like this, for example (I'm using Python-like pseudocode here):
layout = FormLayout(
Section(
title=_("Account information"),
contents=Column(
Field("username"),
Row(
Column(Field("password")),
Column(Field("password_repeat")),
),
),
),
# etc. you get the idea
)
Now, how would I go about rendering this into a tree? If I were to take the approach that the article suggests, I would have to do something like this: def render_element(element: Element) -> SafeString:
# Let's use Python 3.10's match as an analogue for the Dart switch
match element:
case FormLayout(children):
return "".join(render_element(child) for child in children)
case Column(css_class, children):
return format_html(
'<div class="{css_class}">{children}</div>',
css_class=css_class or "col-md",
children=mark_safe(
"".join(render_element(child) for child in children),
),
)
# case Row, Field, ...
As you can probably tell, this is bound to get super unwieldy over time. And this is just for one property of this HTML form builder; now imagine if we had to do some operation to the tree (like checking all fields in a form are actually rendered)!You might, at this point, suggest that we could just split the behavior into different functions... and that would just make us re-implement the dynamic dispatch system that's found in object programming already ;) You can see how we tend to move the behavior to the object in this case, because it lets each object only worry about its own behavior.
I hope this helped with giving a bit of an idea of why I'm for a more object programming-based approach over the pattern matching described in the article.
I've realized that things always need to change in unexpected ways. Objects are sticky, people just cram stuff into them instead of re-thinking the hierarchy properly.
There probably exists a really nice and cleanly separated object-hierarchy for a codebase at a given point in time, but requirements always evolve too rapidly to enjoy this for too long.
To get a better idea of what I think is the better approach, check out these talks:
Tudor Gîrba - Moldable development - https://www.youtube.com/watch?v=Pot9GnHFOVU
Jack Rusher - Stop Writing Dead Programs - https://www.youtube.com/watch?v=8Ab3ArE8W3s
layout : Element → SafeString = FormLayout
[ Section
{ title : _ "Account information",
; contents : Column
[ Field "username"
; Row
[ Column [ Field "password" ] ]
; Column [ Field "password_repeat" ] ]
]
]
}
(* etc. you get the idea *)
]