It strikes me as bad design if something as simple as an action (hit) now needs to become it's own class that is instantiated merely to execute a single function and then have to delete itself. That just feels like insane overhead/boilerplate, no?
The argument here is that it's far better to have player and monster be simple data structures, and a single function hit(player, monster, weapon).
It is needless complex if the code is simple.
This solution is more flexible that just a pure function. If you have different players who use different hit strategies how do you handle that with just a pure function? Lots of if statements in the function? Passing in lambdas in every case you call the function? Then you could curry the function and call it something different too and that works I guess. OOP shines when you have lots of different ways things can work in different combinations. OOP is a tool like other programming paradigms, you use it when it solves your problem better than the other ways.
I'll list a few strategies I've seen in different contexts:
1) Clojure has "protocols", which is a strategy of doing polymorphism where the verb is charge instead of the noun.
2) Rust has trait objects, where you have to implement the polymorphic behavior you want for a separate player type but the data is separate from the behavior and not interlinked or owned by the class. You can implement the behavior in the scope of the module where it is used.
3) You already mentioned this, but lambdas in Javascript or functors in C++ satisfy a lot of specialization requirements.
All 3 of these approaches are different ways of approaching the problem of different behavior on the same data. The key thing with them is that it allows domain specific behavior to be decoupled from an owning object. There may be reasons that OO is more suited to a problem (as you mention), but I tend to agree with the author's post around the dogma of using OO everywhere.
In the article, the author also mentions a quote around encapsulation
> Encapsulation is an object-oriented programming concept that binds together the data and functions that manipulate the data, and that keeps both safe from outside interference and misuse.
In my opinion, this view of binding the data and behavior together stems from an idea that data is scary and can be changed at any time. In an immutable, pass-by-value, functional world, those getters and setters and indirection is just another thing in my way from composing the data together with collections tools I am very familiar with. I think it was Neal Ford who said that "OO encapsulates moving parts, whereas functional programming removes moving parts." I think that's very appropriate in this context. In a data-first view, you model what properties and data shapes you care about in your records, and then you create little functions that connect those things together; in OO, you create the links first through methods (even if those have interfaces), and you're stuck with those connections anywhere you want to pass the object.
OO makes sense if the different types of behavior map to object identities and inheritance trees, because it generates a chain of implicit if statements that capture this logic. If they don't—e.g., a hit changes behavior depending on whether the attacker is proficient in the weapon, rather than depending on the weapon class or attacker class itself—you're likely better off writing the if statements yourself.
Why, it's a noun in the problem domain. Why shouldn't it be a class?
> that is instantiated merely to execute a single function and then have to delete itself.
This may be inefficient in some language implementations because of limits of optimization, but there is no fundamental reason that, if that's all you do with it, the compiled code or runtime behavior needs to be much different than if it were just a procedure call.
On the other hand, lots of times you will want to do more than that with actions occurring in the domain then executing them (queueing, logging/serializing, etc.) and having a datatype for the event (a class in class-oriented OOP) supports that.
Naturally it's better to be simple if the logic involved actually is simple, but surely the point of the example is that game logic typically isn't. Hits in games don't just change a hit-point value, they tend to play animations, trigger events, work differently depending on this or that piece of global state, etc.
hit(player, monster, weapon, damage_modifier, arena, previous_turn, next_turn, global_modifiers)
because the author didn't like, or understood encapsulation.
Poor design has a way of cutting across programming paradigms, or even (in the case of inappropriate inheritance, for example) leveraging their features.
I don't get the adhocness of the example.
> Player.hits(Monster).with(Weapon)
I think games are a particularly pathological case for OOP, and as such probably not a good example for the article's case. But FWIW, the problem with what you describe (and with OOP for games generally) is that game logic tends to be way too polymorphic for code like that. That is, players don't just Hit() monsters, they also hit items, traps, breakable terrain, etc., and they get hit by monsters, by projectiles, maybe explosions, fall damage, etc.
And the dilemma of doing all that in OOP is, you find yourself with 20 different things that can receive a Hit(), that have little in common otherwise. Some have hit points but others don't, some don't have an armor value, some need to receive knockback but others don't even have a physics body, etc. As a result, do you make Hit() accept 20 different types, with special cases for each? Or do you rejigger your class hierarchy so that those 20 classes all inherit from Hittable, etc? Either could work in this or that case, but neither's much fun.
This is all why ECS (or other aspect-based approaches) are so popular for games - they let you define very general "Hit(src, tgt)" chunks of logic, that don't care what type each object is, but can easily query whether or not they have hit points or a physics body.
But again, I think games are a pathological case here and none of this should necessarily be considered an argument against OOP generally.
(Of course, you can wrap everything in a fluent-style interface either way - that part is orthogonal to all the rest.)
It was great while Moors law still lasted, and to write efficient software was becoming some strange quest for some formula one fields of software like games or other massive workload fields like OS-Wizzardry.
Today, the massive workload is still growing, due to sloppy architectural habits and user demands, but the saviors of parallelization and new chip technologies have not come to rescue the sloppy-devs from the laws of leaky abstraction.
Your code runs on a hardware system.
And currently your code is running out of hardware.
And with that OOP is running out of excuses.
So you would write this. Then it would three months before the shipping be handed to some adult- and this adult will delete it. All of it.
Its full of references, full of class-bloat which will push one another out of the cache. Even though the compiler will try to yank the worst out this mental crutch out of the code. Some references can not be dismissed deterministically, so they will be kept. Which makes it incredible slow.
What replaces it will be a efficient structure, keeping all the chunks necessary for collision detection, in one very array like field.
Over this a Algo traverses, acting with a function, which does not reference non-local stuff, detecting collisions and damage. Allowing not only for a few players- but a workload of players.
It will look very ugly, like C, with inline assembler- ugly, and it will be ready to ship.
A common but false statement. Firstly, there is no standard definition of OOP, only loose sets of features that define various overlapping but disjoint paradigms that some subset of people call OO. So your statement is meaningless as there is no single OOP that we identify as how "people see the world".
Secondly, even given any specific definition of OOP, it's also false. There are many programs that simply aren't suited to OO modelling, because you want to express things as the problem being solved actually requires, and this is often not OO. Sometimes pattern matching is best (compilers), sometimes reactive/event paradigm is best (servers, UIs), and neither of these are OO, as but two examples.
And don't take my word for it, there are a few studies on novice programmers showing quite clearly that event-based temporal reactive primitives are what people find most intuitively natural, ie. when account balance <= O then do some action, which is a declarative reactive action that will execute when that condition becomes true. This is not an OO program in any sense.
And this one line is why you're willing to setup all these crap boilerplate supporter classes and take a huge hit in runtime performance?
I didn't say it was the "right" way to do it. Also programming is the art of tradeoffs. If this does actually give bad performance, maybe it's a trade off the programmer is willing to make.
Just like the article started off with "I don't think there's a silver bullet". OOP is a tool just like any other with pluses, and minuses.
Also the Hit class may be a Singleton and only instantiated once.
Hits don't usually happen that often in games relative to everything else the engine is doing unless you're writing something like MMO server code that processes hits from thousands players.
Yours is a classic case of over-optimizing, I think.
Imagine there are hundreds of ways Hit can be implemented and used in different situations. That's the reason for breaking out this type of abstraction. I agree this example the author used isn't probably a clear one in which one should use OOP.
This is the typical argument you get to hear from OOP apologetists. And the codebase is rotting, just for concerns about hypothetical problems...
I remember one time when I was criticized for putting in too much global data and not enough classes "because what if we have two GUI instances?". The guy of course had no idea why he would want that, and how it should work.
Besides, if we really want to be snarky, why haven't you wrote it in assembly for performance?
Why not in assembly? Because it's not worth the effort. You won't notice any difference in speed. Be pragmatic.
The moment your game needs to know anything else about that hit event, you're going to start creating side effects from that procedure and that QUICKLY snowballs into spaghetti code. Not to mention, just from the signature, that's going to be an absolutely huge procedure.
>Because it's not worth the effort. You won't notice any difference in speed. Be pragmatic.
That's the exact same case I'm making. A hit object every so often will have no impact on performance (certainly not a huge impact) like you originally said and you gain developer productivity.
> Not to mention, just from the signature, that's going to be an absolutely huge procedure.
How do you intend to write less code with OOP?
Now an environment flag causes fire damage to deal +10% more. You're either going to have to extend the hit method again (further complicating it), or just pull that flag from the environment class in the procedure body itself (undeclared dependency). When something else outside monster/weapon/damage/environment has to change the hit calculations, you'll have to extend it again and again.
>And yes, the procedure probably has "side effects". Because that's the point.
Side effects are terrible for maintenance and debugging, you shouldn't be using that to defend your argument here -- unless you don't know what side effects are which is why it's in scare quotes?
>How do you intend to write less code with OOP?
The point is for it to be more human readable because it's unlikely there's performance impact in this case. You don't want to count code quality by lines/characters of code.
When something should change, you edit the freakin' code. There is no way around it. If you have different kinds of hits then you make different procedures. e.g. magicPixieDustHit(monster, pixieDust, weapon, damage).
> Side effects are terrible for maintenance and debugging
FP apologetists want to make you believe that, but side effects are the actual point of the program.
> The point is for it to be more human readable
hit(player, weapon, monster)
Player.hits(Monster).with(Weapon)
I mean at least acknowledge that that's a highly subjective statement...I dunno, maybe aim for something a little better than writing an exponential amount of functions for all of your interactions.
>FP apologetists want to make you believe that, but side effects are the actual point of the program.
If you want to make all of your co-workers hate you because randomProcedure changes shared state when it shouldn't, go right ahead. If you want to stop that, you're like two steps away from OOP's dependency injection when you write validator functions on the shared state object.
>I mean at least acknowledge that that's a highly subjective statement...
Games are about the worst choice for criticizing OOP because OOP is so useful for describing games. Procedural style is fine for Pong or Sudoku or really simple games, I guess. It's highly subjective in-so-far as the entire industry has mostly adopted it and released great games with it.
You mean "polynomial". And you are still not acknowledging that OOP doesn't help there either. There is only one way out: You as the programmer must do the sensible thing. If you really need runtime polymorphism (which you rarely need, if you structure things correctly and keep separate things separate), then for god's sake go ahead and do it. But in my opinion it's much cleaner to do it with explicit function pointers.
> Games... > the entire industry has mostly adopted it and released great games with it.
I think you are at least 10 to 20 years late. The games industry, especially in the AAA sector where performance is critical, seems to long have acknowledged that OOP doesn't work out.
at least in C++, why would they ? it'll all gets inlined and you can do it so that there isn't any memory allocations if you know all of your cases at compile time (of course most of the time you want to be able to add new weapons, behaviours, etc, at runtime but in game engines you generally use scripting languages for this anyways).
I wonder if some of this disagreement is down to the way that different people abstract this problem in their heads.
// player.hits(monster).with(weapon)
add to class Player {
// XXX: Bad coupling Player -> Monster
// XXX: Bad coupling Player -> PlayerMonsterHit
method hits(Monster monster) {
return PlayerMonsterHit(player, monster)
}
}
class PlayerMonsterHit {
member Player player;
member Monster monster;
construct PlayerMonsterHit(Player player, Monster monster) {
this.player = player;
this.monster = monster;
}
method with(Weapon weapon) {
doTheActualFrigginHit(this.player, this.monster, weapon); // this line is all we REALLY need
}
}
I guess 15 lines (that do NOTHING) was not an overestimation.Yes – this code is stupid if all you need to implement is a single line with the ability for a player to hit a monster. But that's never what you are implementing, is it?
struct PlayerMonsterWeaponHit {
Player player;
Monster monster;
Weapon weapon;
}
Array<PlayerMonsterWeaponHit> playerMonsterWeaponHits;
doTheActualFrigginHit(Player player, Monster monster, Weapon weapon) {
playerMonsterWeaponHits.emplace(player, monster, weapon);
}
In case it isn't obvious you can do that with either implementation, the above OOP boilerplate or the above imperative 1 line of code.> Yes – this code is stupid if all you need to implement is a single line
No, it's stupid because it doesn't do anything. The data structures are only for temporaries that will never have any other use. In the end it's going to be PlayerMonsterWeaponHit. So the other classes are just stupid, and no amount of context will change that.
This is not essentially different from what happens in non-OO code. OO purists would probably object to this as a violation of encapsulation, and would insist on objects receiving a hit performing the update to their state themselves.
Stepping back from this example and considering transactions in general, it is often the case that there are certain constraints to be observed, and in such cases, it is easier to verify the solution if it is done compactly in one function. In such cases, creating a class and instantiating it just to have that function would be pointlessly excessive obeisance to a principle, and making it a singleton would only underscore that point.
There are minor issues when you venture off and decide that it would be cool if a monsters could damage your weapon. Something like Monster.hits(Weapon).with(Weapon). You'll start wondering if Weapon should inherit from the player base class. If not, you'll spend time wondering how to share the code to keep things dry. Obviously there are many solutions even within OOP, but one might consider looking to ECS to remove code duplication and decouple things.
Lots of good examples in the game programming patterns book: http://gameprogrammingpatterns.com/component.html
In that case it may be better to rename it to HitStrategy?
Probably not. If you want to do that, they should both implement an interface (and perhaps share some code through composition) but code inheritance is likely not the right approach here.
The problem is that it's an artificial example, in reality you'll ave a lot of different monsters, weapons, and most importantly separate subsystems. I.e. physics processed in one pass, animation in another, same goes for custom logic and rendering.
Modern game engines use component systems that put data first for the same reasons author described in the post.
I tried the more ”OO”-approaches for all too long thinking it would lead me right. It doesn’t.
https://ericlippert.com/2015/04/27/wizards-and-warriors-part...
Second, in one of the articles I found one of the best quotes I’ve ever heard about when not to use exceptions....
When you’re writing code in the IDE, it is correct code that is the exception!
Not saying this is the right way to do things but, if you're actually going to go 100% OO on something:
Player.hits(Monster) returns Hit
Hit takes a Player and a Monster in constructor, and has with(Weapon)
You end up with:
Player.hits(Monster).with(Weapon)
Then Hit reaches into said objects and deals with changing the HP, and XP. You then have encapsulated the details in the actual Hit itself, which seems correct.
It does read kind of nicely IMO...