by hprotagonist · 5y ago · 0 comments
Q: Why was this was a mistake?
A: When you declare a class that’s a kind of item, it locks you into that structure much more tightly than if you just have member elements. It’s nice to be able to use virtual functions and that kind of thing, but the tradeoffs are just too much. I started using a “tool” item in the hierarchy, which started to get various functionality, and can now support anything from a stepladder to a beehive to a mortar (and pestle, separately, ha ha), and it just feels more flexible, and I wish every crafted item in the game were under that umbrella.
We do a lot of procedural generation, and if we wanted to, say, generate an item that acts partially like one thing and partially like another, it’s just way harder to do that when you are locked down in a class hierarchy.
Preach:
https://ericlippert.com/2015/04/27/wizards-and-warriors-part...
https://ericlippert.com/2015/04/30/wizards-and-warriors-part...
https://ericlippert.com/2015/05/04/wizards-and-warriors-part...
https://ericlippert.com/2015/05/07/wizards-and-warriors-part...
https://ericlippert.com/2015/05/11/wizards-and-warriors-part...
I have certainly committed all of these sins, too.
My policy: OOP is like salt. Use little and that's great. I only allow a single inheritance layer, and ideally no inheritance at all.
That's been my observation as well - there's no free lunch and DRY isn't free either, certainly not if you use inheritance chains to achieve it.
I'm starting to think that the only programming axiom that will survive in the end is KISS.
And what an acronym given the context!
NSM would be the minimum element set of concepts shared by all human cultures, which can be used to derive the rest of concepts, and it's heavily based on anthropological field studies.
And it includes the numbers one, two and many, (also few, some & all). So that indicates some special meaningful distinction for us in that jump from two repetitions to start abstracting away.
But the single responsibility principle and the idea that you should divide your code in components where the lower components should be abstract by the point of view of the higher ones are almost never wrong.
Not by coincidence, those last two are consequences of how people think. While KISS is kind of a physics law.
But as the other reply said, patterns are a language smell - the language needs to support that style and make it idiomatic. Otherwise, if you give people the choice between doing it right but verbosely and doing it wrong but more quickly, guess which one they'll choose. https://www.haskellforall.com/2016/04/worst-practices-should...
In my experience it is nigh impossible to design-pattern your way out of a language simply being unable to express what you need it to express without incurring a severe performance penalty (anathema for game development) or resorting to code generation (which is itself prone to ending up as a Gordian knot).
I have a gorilla class and a banana method on the class, can I ever use banana without the gorilla? No. The simple act of having a class screws it all up.
Make the banana a pure function, or one that is defined in terms of a polymorphic parameter that it mutates.
func banana(x: animal){...}
banana(gorilla);
The way to do it via OOP is base class methods and importing the method to all children via inheritance which is just bad and universally reviled among even practitioners of OOP. class Animal()
{
banana()
}
class Gorilla() : Animal {
}
Technically there are slight fair advantages and disadvantages to the OOP way when you don't account for inheritance and polymorphism but all that is gone once you do account for them.You still don't necessarily need to model the graph at the object level though. You could model your graph as a set of pairs, ie edges. If performance was more of a concern you could do it as a map where each object was a key and the values were a list of the connected objects. You could also separate out the value from the graph behavior and have a GraphNode object that wraps each value object.
The bigger point though is when you have networks of objects that are relying on each other to perform functions, that's where the problem is, and where you start to rely on mocks and stubs for testing, which really should be considered a smell in its own right. Your better off making the interface between objects values rather than having hard references between objects as described in this talk: https://www.destroyallsoftware.com/talks/boundaries. Once the interfaces between your objects are values instead of references you're free to connect your objects together in any way you need and are not stuck with the fixed graph as originally designed.
The trouble is C++ and similar object models poor support for composition and implicitly penalizing uniform object structure.
(E.g. call multiple base methods in a subclass - pain ensues. Add virtual calls to the mix, it gets really iffy.)
Even Python and Ruby with explicit mixins but the old model get hairy.
I'm not being critical either, I'm seriously curious how somebody would implement this behavior in Go. Like you say, just struct with methods is a very appealing mental model since you have fewer moving parts, but how does it deal with a scenario like this which is very common in game dev?
I'm slightly confused about what you're trying to describe, but maybe it's something like this?
https://play.golang.org/p/smPyWvBvWWp
We can make both Food and Animal statisfy the "Animateable" interface.
Go also has a syntactic shortcut which is similar to inheritence, but more explicit. If you include a field in a struct without any name, it is considered "embedded", and you can call methods on the field directly, without referencing its name, which ends up looking the same, at the call site, as inheritence.
https://play.golang.org/p/cIMqQqE0eVc
But everything is still explicitly laid out in the struct -- it's just a simple struct, no inheritence shenanigans.
I think interheritence is a mistake, but interfaces are the bees-knees. Even in C# (which is my main language these days, 'cuz that's what you use if you're making a game in unity), I just use interfaces, not implementation inheritence.
(And even interfaces I don't use much -- but when you need it, you need it!)
edit: You cannot, however, explicitly declare that a "Chicken" is supposed to be a Food and/or an Animal. And you can't directly inherit implementations; to make Chicken directly use a generic function you need to do something like implement "baseSpoil(Food)", and then have the body of "spoil(Chicken)" explicitly call "baseSpoil(self)".
As mentioned in another reply, there is a shortcut. You can declare that the Chicken structure includes (anonymous) Food and Animal fields. Then, if you call "spoil(myChicken)", Go will automatically replace it with "spoil(myChicken.Food)".
By structural typing. It’s a form of satisfying an interface by composition.
Nobody on the face of the earth has ever used Functional Reactive Programming. It's a made up concept. In fact it's also definitely not one of the concepts that inspired the most popular pattern in React.
I would agree to that as a goal, but not as a dogma. It depends what you build, I guess.
I have a player, NPCs, enemies, and wild animals. Should they have any class hierarchy at all? If my code matches the game world, what happens when I was to add golems and let mages turn castle's into entities that act just like an NPC would? Should my class design be so tightly coupled with the elements of my world? I don't think so but what alternative works best?
IIRC I already wrote that here on HN, but I think implementing a simple rogue-like is an excellent exercise to get familiar with any programming language.
They make changing behavior dynamically extremely simple. Instead of needing to hardcode classes for each different type of thing players may want to create in your world, you just assign and unassign components. Give a rock the Moveable component and now it moves. Remove the PlayerControl component from the player and put it on, I don't know, an orc -- now you've implemented body swapping. They're even more useful in a game like traditional roguelikes, where you don't have to worry about animating all these dynamic states.
I've actually never thought about how a component system might fit into a more traditional business application; it's an interesting thought experiment but I'm not quite sure it would be a strong benefit.
https://www.youtube.com/watch?v=wfMtDGfHWpA
I think inheritance makes the most sense when your problem domain has been known for decades - like airline reservations. But for new blue sky projects - you always seem to wind up in these snafus that break your rigid class hierarchy.
is a good read on that... or rather, its a spot to start thinking from.
It ends with:
> A nun of the temple whispered to Jinyu: “This problem has several solutions, but I dislike all of them.”
> “Therein lies its value,” whispered the abbess in reply. “For we are all of us doomed in this profession: our designs may aspire to celestial purity, yet all requirements are born in the muck of a pig-sty. I trust that this monk can succeed when the stars align in his favor, but when they do not, how will he choose to fail? By cowardly surrender? By costly victory? By erroneous compromise? For it is not he alone but the temple that must bear the consequences.”
There are also a set of "topics" hidden with a mouseover at the bottom that can waste a day away without difficulty.
I like the way you put that. Though humans and dogs are 85% similar at a DNA level, so makes sense for them to inherit from a common parent. And my guess is robots and robot dogs would be ~85% similar at a building block level, so dog would inherit from robot.
I think go easy on levels of inheritance but have really strong root classes that most things inherit from.
Good point! Skimmed the blog posts, seemed to have useful enumeration of techniques with considerations.
By creating a tool class you haven't extended the set, you've instantiated a subset of the set of items that contains the items that are tools but nothing else. It's obvious why it is so difficult to represent a tool that is also e.g. a consumable item. The set of items that are both tools and consumables is a superset of the set of tools and set of items. You can't represent it through a second layer of inheritance because it only lets you create a subset of the items that are tools. You obviously have to use multiple inheritance for something like this because it will let you form the set of items that are both tools and consumables. Of course, multiple inheritance is very messy so you should try to avoid it.
Entity component systems are still in a half-baked state, with everyone rolling their own slightly different conceptual model. They're solving a problem, but not solving it well.
One promising direction is getting rid of entities. Components need to link to entities and other components anyway, so one may as well treat entities as zero-size components. Old writeup (not mine): https://github.com/kvark/froggy/wiki/Component-Graph-System
You are essentially describing ECS here. In ECS, entities are nothing but a "handle" without any additional data, normally just an integer used to link common components together.
If entities could be IDs to which components are connected, or containers holding components. Either case has disadvantages.
If entities hold components, then iterating over components means iterating over entities, which slows down all systems. A rare type of component still degrades with adding entities.
If instead components link to entities, and you want multiple components to interact, then these interactions slow down the system because of multiple lookups that need to be done.
Author proposes to use a graph structure between components, getting rid of entities-component duality. Proposes to use pointers which allows calling into any component and process then all required components.
I am not entirely sure if this would solve all problems, but this seems to be the proposal. It seems setting up the graph dynamically would be quite the task, though. For example, I don't immediately see how to guard against cyclic behavior and too many calls into a single component etc.
ECS is so common and easy in lisps that it doesn't even warrant its own name.
https://en.wikipedia.org/wiki/Component-based_software_engin...
"Component Software: Beyond Object-Oriented Programming"
https://www.amazon.com/Component-Software-Beyond-Object-Orie...
Goes until 43:25.
The whole talk is worth watching. It's basically about the higher level problems of business app development, how to address them, and how Clojure does address them.
The only time I used inheritance was while implementing a job execution framework. It fit the pattern nicely.
Its the fragility of large inheritance hierarchies. They work well for very rigidly defined real world structures but not so well in most real-world usages.
Tarn was wrong about this though:
> Using a single object with different allocated subobjects is almost certainly worse for cache misses
It depends a little on the context, but having object pools is exactly the right thing to do when you're trying to scale. It allows you to group together similar data, reducing cache misses when batch processing. You can even cache-align your primitives, or even run SIMD and multi-core jobs to batch update an entire set of attributes that belong to multiple objects.
He also goes on to show a text editor written entirely in the rules engine (which he uses to develop the game in), really cool stuff!
and a bit about multiple inheritance in LPC - http://graphcomp.com/info/mud/mudos/lpc/constructs/inherit.h...
And another bit - http://www.geas.de/tutorial/lpc_57.html
As to seeing it in other languages... this gets into a mixing - https://en.wikipedia.org/wiki/Mixin
An example of that in Scala - https://docs.scala-lang.org/tour/mixin-class-composition.htm... or https://www.baeldung.com/scala/class-composition-mixins
The issue is that for most situations, the additional conceptual load of multiple inheritance gets difficult.
A program that puts a handful of form widgets, consumes a bunch of text or spends most of its time waiting for I/O is far from the same domain.