{"id":21315,"date":"2013-10-11T03:29:22","date_gmt":"2013-10-11T08:29:22","guid":{"rendered":"http:\/\/www.shamusyoung.com\/twentysidedtale\/?p=21315"},"modified":"2015-07-01T04:48:02","modified_gmt":"2015-07-01T09:48:02","slug":"project-good-robot-23-programming-paradigms","status":"publish","type":"post","link":"https:\/\/www.shamusyoung.com\/twentysidedtale\/?p=21315","title":{"rendered":"Project Good Robot 23: Programming Paradigms"},"content":{"rendered":"<p>I didn&#8217;t add much in the way of new stuff this week.  I spent a lot of time refining and polishing and bug-fixing, hoping to get a new build out to my testers<sup>*<\/sup> before the weekend.  I&#8217;m spending a lot of time fussing with stuff I&#8217;ve already written about.<\/p>\n<p><small>* For the record: I&#8217;m SLOWLY adding to my list of testers. I know people will get sick of playing the same broken game week after week, so I&#8217;m trying to add new people as the old ones lose interest.<\/small><\/p>\n<p>So! Let&#8217;s talk about something controversial. Even better: Let&#8217;s talk about something incredibly controversial to programmers, and completely tedious, esoteric, and impenetrable to non-coders! Let&#8217;s talk about <em>programming paradigms<\/em>. Some people have asked about how my program is structured, and since I know the answer will leave some people deeply offended, I might as well discuss the &#8220;why&#8221; before I get to the &#8220;what&#8221;.<\/p>\n<p>Just to bring normal people up to speed:<\/p>\n<p><!--more-->At first, basically all programming was <a href=\"http:\/\/en.wikipedia.org\/wiki\/Imperative_programming\">imperative<\/a>. Programs would be structured in the form of do thing1, do thing2, do thing3, etc. <\/p>\n<pre lang=\"c\">\r\nUseCover (space_marine);\r\nDoShooting (space_marine, machine_gun);\r\nDoYelling (space_marine, gravel_voice);\r\nDoGrumpyFace (space_marine);\r\n<\/pre>\n<p>Or whatever.<\/p>\n<p>The idea being that in the above code, space_marine is probably a structure of properties.  Like:<\/p>\n<pre lang=\"c\">\r\nspace_marine.name = \"Mister Chief\";\r\nspace_marine.bullets = 999;\r\nspace_marine.hitpoints = 100;\r\nspace_marine.run_speed = 1;\r\nspace_marine.height = 1.8;\r\nspace_marine.dead = false;\r\n<\/pre>\n<p>By calling this code, you&#8217;re doing things TO the space marine. Also that code might also make changes to other things that are NOT space marines. Basically, you can&#8217;t look at this code and know what parts of the game state might change. Maybe nothing. Maybe many things. The space_marine might die. It might win the game. It might trigger a change to the next level. It might destroy a dozen other in-game things. As a programmer, you just don&#8217;t know how the state of the game might be changed or what sort of things might happen. You have to read the source. This is technically true of all languages except for a few built around the <a href=\"http:\/\/en.wikipedia.org\/wiki\/Functional_programming\">functional programming paradigm<\/a>, but its <em>particularly<\/em> true of imperative languages. <\/p>\n<p>The problem we have is that in a big project, our marine will end up having a LOT of properties. In Good Robot, each robot has over 50 properties like this that keep track of what the AI is thinking, when the weapons are ready to fire, how it&#8217;s moving, etc. And this is a simple little 2D game. In a 3D game with more complex geometry, multiplayer, tons of weapons, vehicles, and multiple game modes, we&#8217;re likely to have a lot more. <\/p>\n<p>In imperative programming, we&#8217;re likely passing around this space_marine variable to every system that needs it, and any system can make changes to any part of it. So maybe some other programmer comes along and writes the grenade code.  Not understanding this structure I made, he just subtracts damage from hitpoints and calls it a day.  The problem is that he doesn&#8217;t update the &#8220;space_marine.dead&#8221; variable. So now we have a bug where grenades can damage you but they can&#8217;t kill you. <\/p>\n<p>Maybe he wants the grenade to blast you up in the air, so he just adds a bit to the &#8220;space_marine.height&#8221; variable. Except, that&#8217;s not how that variable is used. It&#8217;s not your height off the ground, it&#8217;s how tall you are. So now we have a bug where getting blasted with a grenade makes you incrementally taller. <\/p>\n<p>The problem here is that ANYONE (any programmer working on any section of the code) can make changes to a space_marine.  And thus everyone needs to have complete knowledge of how a space marine works, what all the variables mean, and how they inter-operate. You end up needing every programmer to understand every system in perfect detail, and that&#8217;s just not reasonable. It&#8217;s not even possible in most cases.<\/p>\n<p>Worse, you&#8217;ve got a lot of side-effects going on.  When someone notices that one character is slightly taller than another, they do some testing and find their space marine is 30cm taller than he should be. How did that happen? Anything that interacts with a space marine would have access to those variables. Which system is fiddling with the height? Saving the game? Starting a new match? Entering or exiting vehicles? Something with networking? Running, jumping, using cover, picking up weapons, dying, using guns, melee attacks, taunts, dying, leveling up, rendering, being healed, being damaged, chatting, or performing emotes? It could be ANYWHERE in the game. Have fun finding it.<\/p>\n<p>So then we have Object-Oriented programming. The idea is that we lock away all those marine properties and other programmers can only interact with the marine through the interface:<\/p>\n<pre lang=\"c\">\r\nspace_marine.Damage (grenade_damage);\r\n<\/pre>\n<p>So other programmers can&#8217;t modify hit points directly. They don&#8217;t need to know that the variable &#8220;hitpoints&#8221; exists, how it&#8217;s used, or about the &#8220;dead&#8221; flag. They just send damage values to the marine and the marine object takes care of the fussy details. It knows to kill itself if its hitpoints drop below 1, and it knows what animations to kick off, scores to change, weapons to drop, etc. Other programmers don&#8217;t need to know any of it. If another programmer wants to blow the space marine up in the air with an explosion, they won&#8217;t have access to the &#8220;height&#8221; variable but they will see something like&#8230;<\/p>\n<pre lang=\"c\">\r\nspace_marine.Shove (direction);\r\n<\/pre>\n<p>&#8230;and realize THAT&#8217;S what they should be using to shove the marine around the environment. The object&#8217;s interface will guide this other programmer and stop them from doing something destructive.<\/p>\n<p>This process of hiding the inner workings of an object is called <em>encapsulation<\/em>. This is a good solution to the above problems. It is not, however, a good solution to <em>every<\/em> problem.<\/p>\n<p>Java adheres to the Object-Oriented paradigm with unwavering strictness. Everything is an object, owned by an object, owned by an object, yea, even unto the n<sup>th<\/sup> generation shalt thy objects be owned.<\/p>\n<p>So you end up with this thing where you&#8217;ve got a &#8220;game&#8221; object. Just one. And it owns a &#8220;game session&#8221; object, which owns a &#8220;level&#8221; object, which owns a list of &#8220;space marine&#8221; objects.  <\/p>\n<p>Okay, fine. Now we&#8217;ve sealed everything off so there aren&#8217;t any side-effects, every object is owned by another, and objects can&#8217;t change each other. The problem is that there aren&#8217;t any side-effects, every object is owned by another, and objects can&#8217;t change each other. <\/p>\n<p>Like, if I want my space marine to create a little cloud of dust when he stomps on the ground, who owns that? If the marine owns it, then killing the marine will make all of his dust particles instantly vanish, which would look odd. If he kicks off a sound effect, I might not want that sound effect to die with the marine. If he&#8217;s supposed to drop his weapon on death, then marines need to be able to give the object to some other system. <\/p>\n<p>Obviously we can&#8217;t have marines owning their own visual effects, sound effects, and particle effects. So we have to&#8230; what? Make a &#8220;sound effect&#8221; object and have it owned by&#8230; who? The game? The level? Should we create some master sound-owning object to act as an MC for all the sounds the game is making? Should we make a particle wrangler that keeps track of all the particles?<\/p>\n<p>If we make one particle wrangler object that&#8217;s in charge of all particles, then we&#8217;ve basically re-created all the old C-style imperative design but now it&#8217;s just WAY less convenient to use. We can&#8217;t just call PaticleCreate (stuff), we have to get the game object, which will give us the session object, which will give us the level object, which will give us the particle wrangler. <\/p>\n<p>Also, my space marines need to collide with each other. Collision is incredibly complex. To collide A with B I need access to the polygonal structure of both, the skeleton of both, the current state of both, what each one is doing (I shouldn&#8217;t be able to shove someone if they&#8217;re attached to a mounted turret or behind the wheel of a car) and how they&#8217;re currently moving. Do I have the level object (which owns all space marines) run the tests and make the marines bounce off each other?  But then we would need to expose all of the inner workings and logic of the space marine, which is exactly the thing we were trying to hide. Or do we have marines themselves try to bump into each other, in which case each marine needs to be able to find all others, meaning marines need access to the data structures of their owner. We also need a way to avoid duplicate tests so that once we test for A colliding with B we don&#8217;t waste CPU testing if B has hit A. <\/p>\n<p>No matter which way you go, you have to poke some major holes in your encapsulation to do this efficiently, and we&#8217;ve just scratched the surface.<\/p>\n<p>Weapons need pointers to the marines carrying them, vehicles need two-way access to marines so they can both be driven by and run over them. Marines need access to each other and all the other objects in the game. They all need pointers to the game object so they can access game rules, but they also need a pointer to the current level so they can do collision with the level geometry. And even though the game owns the level, you probably want direct pointers to both since drilling down through levels of pointers owned by pointers can cost you performance if you do it enough times (many objects) or if the layers of objects-owning-object-owning object is annoyingly deep.<\/p>\n<p>In the end, we&#8217;ve imposed this rigorous top-down structure and then we spent days or weeks writing code to get around or through it. In a world of pure theory, an object hierarchy makes perfect sense and there&#8217;s always a &#8220;right&#8221; way to do things. Objects can hide behind their interfaces and we never need to worry about their innards. In practice, the right way is not always clear and even if you&#8217;re lucky enough to nail it, you may find it requires many transgressions against object-oriented design. You can end up with something that&#8217;s just as unsafe and exposed as imperative programming, while also being more cumbersome, convoluted, and perhaps even slower. <\/p>\n<p>In a lot of cases, those &#8220;protective layers&#8221; of OO design don&#8217;t actually protect you from anything, because you have to poke so many holes in it that the thing no longer serves the intended purpose. <\/p>\n<p>All of this is to say: I am not a purist when it comes to OO design. <\/p>\n<p>For years I thought  I was bad at OO programming.  But then I realized that some problems just don&#8217;t lend themselves to an OO solution. In my own code, I manage to infuriate all parties by mixing C++ style object-oriented design with C style imperative. If I&#8217;m going to make many of something (robots, sprites, lasers, explosions) then those things are a class. If I&#8217;m making ONE of something (like the game, or the gameworld) then it doesn&#8217;t use any kind of class interface at all. <\/p>\n<p>This makes it easy to manage large groups of things, but also prevents me from accidentally making more than one of something when more than one would violate the design and common sense. <\/p>\n<p>A good example is the player. Right now you call <code>PlayerUpdate ()<\/code> to process player input. This performs non-repeatable actions and creates state changes in the I\/O. Sure, I could make a <code>class Player p;<\/code> and call <code>p->Update ();<\/code> but that would make no sense. Like, if you had more than one player object, the first one would eat all of the mouse and keyboard input, leaving no clicks, mouse movement, or key presses for the other. Having more than one player is an impossible and nonsense state, so why make it possible? The presence of <code>PlayerUpdate ()<\/code> makes it really clear how this should be used. <\/p>\n<p><em>Q: But Shamus, what if you wanted to make the game multiplayer?<\/em><\/p>\n<p><strong>A: Then I&#8217;d have to re-write the player code. That would be true regardless of whether or not I was using a class interface. Since multiplayer isn&#8217;t even being considered, I don&#8217;t see any percentage in spending time making it easier to add features that I&#8217;m not going to add. That&#8217;s like spending money to put a boat hitch on every car you own, just in case you end up buying a boat someday. <\/strong><\/p>\n<p>Boom! Crappy car analogy. It&#8217;s been too long since the last one. <\/p>\n<p>Getting back to classes. Even when we DO want more than one of something, that doesn&#8217;t mean I&#8217;m going to make it a full-fledged class.<\/p>\n<p>If something is a container for variables (like XYZ vector data or RGBA color data) then I make it a struct with public members. Making wrappers for individual entries in this case makes no sense to me. When I was using Qt, I didn&#8217;t bother with their built-in vector types because some silly OO zealot thought that this code&#8230;<\/p>\n<pre lang=\"c\">pos.x = pos.x - (pos.y * pos.z);<\/pre>\n<p>Would be SO much better as:<\/p>\n<pre lang=\"c\">pos.SetX ( pos.GetX ( ) - (pos.GetY ( ) * pos.GetZ ( ) );<\/pre>\n<p>Oh man. That still drives me crazy just looking at it. What&#8217;s the purpose of that stupid interface, anyway?  If that&#8217;s a good idea, then why not:<\/p>\n<pre lang=\"c\">\r\nint a.Set (b.Get () + c.Get ()); <\/pre>\n<p>&#8230;instead of <code>a = b + c<\/code>? So much safer! Screw convenience and compact clarity, we must mindlessly adhere to class-based orthodoxy! <\/p>\n<p>My rule of thumb is that if variables change each other (say, setting &#8220;m_age&#8221; will impact the value of <code>bool m_is_senior_citizen<\/code>) then it needs wrappers and the members should be encapsulated. But if the members are independent then it&#8217;s just a container for values and the other programmer should be trusted to know what they&#8217;re doing.  A class interface is there to hide complexity.  But if there is no complexity then the class interface might hide the fact that there is no complexity! <\/p>\n<p>So to answer the question:<\/p>\n<p>Robots are a single class.  The only &#8220;fancy&#8221; object inheritance stuff I&#8217;m doing is I&#8217;ve got a base class from which bullets, missiles, explosions, and powerups, are derived. Objects in the program can create these entities and then hand them off to the world management code in world.cpp.  <\/p>\n<p>So that&#8217;s it. Mostly C-style structure with a few dozen C++ classes being thrown around. In places where I do use classes, the interfaces are very tight. <\/p>\n","protected":false},"excerpt":{"rendered":"<p>I didn&#8217;t add much in the way of new stuff this week. I spent a lot of time refining and polishing and bug-fixing, hoping to get a new build out to my testers* before the weekend. I&#8217;m spending a lot of time fussing with stuff I&#8217;ve already written about. * For the record: I&#8217;m SLOWLY [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[498],"tags":[],"class_list":["post-21315","post","type-post","status-publish","format-standard","hentry","category-good-robot"],"_links":{"self":[{"href":"https:\/\/www.shamusyoung.com\/twentysidedtale\/index.php?rest_route=\/wp\/v2\/posts\/21315","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.shamusyoung.com\/twentysidedtale\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.shamusyoung.com\/twentysidedtale\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.shamusyoung.com\/twentysidedtale\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.shamusyoung.com\/twentysidedtale\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=21315"}],"version-history":[{"count":0,"href":"https:\/\/www.shamusyoung.com\/twentysidedtale\/index.php?rest_route=\/wp\/v2\/posts\/21315\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.shamusyoung.com\/twentysidedtale\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=21315"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.shamusyoung.com\/twentysidedtale\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=21315"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.shamusyoung.com\/twentysidedtale\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=21315"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}