Thirteen Years of Bad Game Code
etodd.io
etodd.io
If you accept that your best is your best, then your best is good enough. The effort is what matters.
Not necessarily true, if you're (trying to be) a professional then it might not be enough.
String myBoolean = "yes" boolean alanIsABastard = true;
As I was the only person in the company with that name it was clearly meant for me! :-) public class ClassWithBadNoGoodNameForSharingStuffCommonToHandlers { //TODO rename
One day soon, I'll figure out what abstraction it represents and rename it... public void encryptCreditCard(int[] cc) {
int tmp = cc[0];
cc[0] = cc[6];
cc[6] = tmp;
// and so on...
}
Decrypt version just did the steps in reverse, of course.Sometimes, of course, you write code that is just right, and it still is after a year.
But, yes, that "What-was-I-Thinking" moment happens on a fairly regular basis. ;-)
In the grand scheme of things you'd hardly notice that it takes me a little bit longer. Over time those improvements become habituated and I just do a lot of them while I'm coding. Especially when I get stuck.
It's not in like cleaning while you cook. Once you have a tempo it hardly takes any longer to prepare the food but you don't leave yourself with a mess that discourages you from doing it again.
Insist the person documents all the quirks and gotchas in a block of code or library. Sometimes the embarrassment at having to justify it will prompt them to fix the problem, other times they (or I) will realize that it literally takes less time to fix the issue than it does to apologize for it.
Something about the writing process unearths simpler solutions to tricky sounding problems. Possibly the same phenomenon that TDD tries to exploit.
Sadly those instances are fewer than those where my old bad code is literally just bad.
We've been in this situation lots of times, where we'll write some code, then finish the solution after a few days or a week, then look at it a month later and say "Wow, this is really not a good way of doing it," only to spend another few days or weeks rewriting it.
The idea of spending 10 minutes drafting a solution, throwing it out, spending another 10 minutes on diagrams and guesses, throwing it out, typically gets met with "Just _code_ damnit," but, diagramming could compress months of rework into minutes.
I suspect quite a few developers who "just code damnit" follow this same process too. After all, it's not exactly hard to rewrite code and with tools like Git in place you can easily stash the different implementation methods so you're not having to lose any work during the cycles.
Usually when bad code gets written by experienced developers it's not so much because of a lack of willingness to conceptualise the design but often just because either the deadline is sufficiently tight that you are forced into writing a "quick fix" rather than something robust. Or because the code base is already an mess (due to the evolution of the product and the aforementioned issue of quick fixes) which means the "ideal world" solution is a significantly larger undertaking than it should be and best not undertaken while you have deadlines depending on it. Or sometimes you see "bad" code simply because the aim of the project is a minimum viable product or proof of concept, thus it's more about proving the product works as a concept than the implementation of it. In that scenario it can make a lot of sense to throw quick code at a problem with the understanding that chunks of the application will be revisited when you start to scale the product.
...and remember that the "rewrite" is similar to an even older version that you temporarily forgot about.
As I've matured as a developer, I've taken to commenting much more heavily. However, I focus more on capturing why I'm doing something, which sometimes includes why I didn't do it a particular way.
In my past few contracts, the devs at each shop fell cleanly into the overcommenting or never comment school of thought. Many old time C coders hate or love comments for exactly the opposite reasons as new grads writing Javascript or Ruby, and when conversing most argued that the code should explain itself. It is very hard to make code explain why because it is doing what it does, and this tiny nuance is hard to grab.
One job we kept reintroducing the same bugs and the customer was furious. I started reading the version histories more closely and figured out two developers were dueling over two separate bugs in the same block of code. Each would reintroduce the other' bug. Since then and due to some other experiences, I spend time looking at how the code arrived to deduce why it was the way it was. I pride myself on a low regression rate and this helps a lot.
Note that if you value quality over quantity, you're self -selecting for writing less code but in more critical parts of the application, like libraries or cross cutting concerns like security or localization. And you also have to accept that if you insist that everyone on the team coded like you then nothing would ever get done. The last bit is, IME, the hardest part.
Unbeknownst to me, a defect was entered and another programmer made a change. It wasn't really a bugfix but more like a change in the desired functionality. His change worked perfectly well but I wasn't made aware that someone else had changed the code. When I was assigned another defect, I used the version of the code that I had from my last checkout to make the change. When I checked in, I overwrote his change.
We quickly discovered this during testing and I reverted my change. I used his last checked in code as the basis for my change and all was right with the world but we had a confused user and two confused programmers for a couple of hours.
That's a young mans game, after you've been doing this stuff long enough the things you learn are in terms of systems design, maintenance, etc. I regularly go back to code I wrote 2 and 3 years ago and think to myself "knowing what I know now, that code is mostly alright".
I can't understand how someone can go back and look at some authentication code, for example, and think the way they did it was horrible. Just how many different ways can you write auth code?
It's one thing if you're a young developer, but at some point the improvements to your code are negligible and have nothing to do with the value you bring to a project.
The thing is, if you're going back to the first time you've ever "programmed time", then what you're assessing is design, not code, which falls in line with what I said.
[edited to remove typo]
Why?
To paraphrase someone else: I wrote sufficient code because I didn't have the time to write good code.
There's always a better abstraction I could have teased out, a more complete refactor to make that one line hack never have to exist, and better documentation which would read more like English and less like shorthand.
(I'm saying this as someone who's been coding in C++ for over two decades, while still finding lots of room for improvement in my older code.)
The analogy I'm experimenting with now is stage performers for Opera or Musical productions. If you see them up close, such as video recording, they clearly 'overact'. They use exaggerated facial and arm expressions to project their performance far enough so the people in the middle or even the back can see what's going on. They are expanding the audience greatly, but admittedly at the expense of those closest to the action. But on the whole it's a better performance.
When I find bugs in my code, introduced by me or added by someone else, I think about how it looked before and try to determine if it was just a dumb mistake or whether I tricked them into it. Maybe I grouped the code oddly, or chose an unfortunate variable name that implied something else was going on. If it's the latter I think about whether I really want to use that pattern anymore. What's tricky is that everyone tries to make their code look like the existing code, so people may be copying the pattern thinking it'll get them a clean code review. If I think the problem is bad enough I may stop and refactor all the places it's used (it only works if you're really, really practiced at refactoring), otherwise I'll just make a note so stop doing that in the future. I might mention it in a team retro.
I want my code to be as plain as it can be and still get the job done. Indeed at this point I positively fume when a 'senior' developer writes clever code, because they should know by now this isn't about them and they're hurting the entire team trying to fluff up their own ego. Look how important I am that you need me to fix all the really hard bugs. Fuck that, and fuck your dazzling bullshit. The only thing that pisses me off more is a manager that thinks 'blame allocation' is a viable management style.
He explained to me that the exercises were not being abandoned at all. They were being refined gradually over time. He had one goal, which was improving the uptake and resilience of brain and muscle memory for music. Every refinement was an opportunity he'd spotted, deep in his own mental language, to hone in on that goal.
The way my coding style (both deep and superficial) changes continuously over time always reminds me of the way my father taught piano. My goal, roughly, is to find the perfect balance of clarity and brevity, while maximizing the ease of continued development. My 27 years of practice has resulted in a long chain of insights about how to achieve that. It's always changing. The way I wrote code 8 months ago wasn't wrong, but I found a set of principles that's better. It wasn't bad, but I would not write in that style today. Why would I? I've learned things in those 8 months.
Not at all. I started my first real project in September 2015, had a release out by mid-November. And the code worked, really well. I was praised by users of the software for how reliable it seemed to be. Now, 15-16 months later, I can definitely see the warts - there's a lot of global state, some crackpot abstractions and if I ever want to add new features to it I'll have to do some spring cleaning. But at the same time... it still works. The design is appropriate enough for the needs of the project and its functionality.
One of the unfortunate outcomes of the job market encouraging job hopping for salary bumps is many new engineers don't get the opportunity to see the cost of their own mistakes.
I can be horrified by something I'm writing right now, and if I check that code much later, remain horrified and add ashamed to the list.
But if I write code that I feel is good, then after ten years it is still clear code, concise and easy to understand, therefore, still good.
May be I am not learning fast enough. But everyone can easily understand my code.
The whole topic of global state is very interesting and one I approach cautiously. I'd love to hear what more experienced programmers have to saw. When I go with global state I usually rely on someone else's judgement and use a framework. Like OpenGL and the graphics pipeline has global state.. and I'm okay with that. I use Cinder/Arduino, those things have some global states and for good reasons as well.
But you really try your best to find a stateless solution - and here is feels like he isn't really trying
Game development is kind of different, in that it's rendering the state of a simulation; so aiming for completely stateless solutions ends up making code quite convoluted -- you're hiding state rather than getting rid of it, in my experience.
Now, stateless functions are still well worth it, at least up until it's time to get it optimised for performance ;)
Game development is a fascinating world where a lot of the things I would normally reach for don't apply quite as well. It's quite likely you know all of this already, but I found learning this myself absolutely fascinating, and one of the reasons I still like to tinker with game development in my spare time :)
EDIT: to clarify, I mean the code I write, not my career prospects.
Granted, there was a lot I've picked up over the past few years working for large corporations, but not all of it was good. And there's just as much awful code in business applications as there are in game applications, and it's even less fun to debug them.
Architectural patterns are pretty similar in both; the primary difference is that in a desktop app, you deal with single user and a lot of impersistent state.
I think they're going for 'immutable' instead of stateless.
Making everything immutable maybe is silly, but it's still a very good goal to have in mind. A continuously evolving system can be designed in an mostly immutable manner as well without sacrificing performance.
In a big picture sense you are trying to have your system be a function of time. And while for efficiency you sometimes should preserve intermediate states, you can typically accomplish that with clever caching systems that are not exposed in the interface. So the design remains "immutable" in a sense
1. Quake 3 relied heavily on global state. It was good design, and the engine produced billions in revenue.
2. Emacs relies heavily on global state. A global variable is a first-class citizen. When a package declares a global variable, it's a contract between the package author and the user that "You may configure the behavior of this package by binding this variable to a new value, then invoking one of my functions." Emacs lisp has language constructs which makes this easier: `(let* ((foo-state 42)) (foo-bar))` will update the global variable `foo-state` to 42, call the global function `foo-bar`, and ensures that `foo-state` is returned to its previous value even if an error occurs and an exception is propagated. In other words, global variables are the interface to a module, just like a module's functions, and global variables are almost never left in an unexpected or invalid state due to errors.
This system works shockingly well in practice. Emacs is basically a gigantic state simulation, and it parallels a game engine quite strongly.
The Emacs Lisp language itself is cumbersome, which has led many to dismiss it as ancient. The true power of emacs has little to do with lisp and almost everything to do with excellent design decisions.
3. The history of programming informs us that those who hold to dogma are quickly made obsolete. Every tool and pattern has its place. A technique that simplifies X in a certain domain will make X far more complicated in a different domain. Context matters.
Those design decisions didn't come out of the vacuum. The ability to patch and modify almost everything at runtime is something that came out of Lisp and Smalltalk, and wasn't even on the map of the (currently) mainstream languages until very recently. Dynamic scoping is something that AFAIK has strong Lisp roots too.
Emacs Lisp is less of an accident and more of an old, old language. Even Lisp family moved on to default to lexical scoping, though it didn't remove dynamic scoping - as in many cases, it's still extremely convenient.
[1] https://web.archive.org/web/20130819160454/http://www.altdev... [2] http://kotaku.com/5975610/the-exceptional-beauty-of-doom-3s-...
Emacs added lexical scoping several years ago. When a global variable is declared in emacs using defvar, in addition to becoming globally accessible, the symbol is also flagged as special. This causes it to use dynamic binding whenever it is `let`-bound, even if lexical scoping is in effect.
I pointed out dynamic binding in order to call attention to a technique that allows global variables to be composed into large-scale systems without being hindered by the problems traditionally associated with global state. But if you'd like more precision, feel free to ask.
Stateless abstractions are great when you can provide them. But the stuff you're building on isn't itself built out of statelessness.
Is it, though? YAGNI comes to mind.
A far more dangerous mindset is to think that when starting the problem you are capable of planning the perfect architecture up-front. Often you don't even know what the problem is. Far better to keep things coupled and simple till you know in retrospect that you need to split them out. Same goes for global state.
This is a hard lesson to learn. Abstraction is seductive.
This sounds off to me; if you assume you'll need to change the architecture later on, aren't you better off starting with a decoupled system that can more easily be changed? Or are you essentially arguing for YAGNI, in the sense that decoupling upfront is potentially useless?
I think the problem is that you don't know where the boundaries of your abstractions should be until you have a better understand of what it takes to solve the problem.
We agree that placeholder code shouldn't commit you to too much, but there are patterns that help you with that.
In the parent, the original decoupling turned out to be less performant (I take it) but wouldn't hinder completing the first draft or get in the way of a rewrite with closer coupling.
This is what I started doing in the last year or two. Now my abstracted code tends to be directly motivated through refactoring the copy-paste stuff, with only a little bit of intentional architecture generated after learning that the abstraction addresses a common concern. It's a very cultivated way of developing the code - picking fruit as it turns ripe.
Even so, some decisions turn out to be extraordinarily hard to undo. One of my great blunders was a poor choice of data structure (too greedy with RAM it turned out.) The more experience you have, the more likely you are to sidestep those fatal early choices, of course.
Majority of blogging is focused on how to use something or describe some final idea/conclusion. They are not bad per se but reading about failed ideas, dead ends etc. - the journey itself that lead to the final shape/conclusion is very valuable.
Probably still do to some extent.
Nice read, and something to reflect upon for all young "fundamentalist". It takes some experience to learn when to bend the rules...
exactly. But, imo, you should do that in one point. Only then you can learn from mistakes, and learning from mistakes is the best learning. At least for me. Same in real life. Many examples, here's one: I'm confident and careful with ultrasharp cutting tools. But only because I cut myself bad a couple of times: before that I was more reckless even though I thought I was doing ok. Also others telling me to be careful had no effect whatsoever.
(Looks at the artbook from collectioner's edition of StarCraft 2.)
And some artists even specialize in sketches and concept drawings.
In the sense of tools in the real world (like hammers, etc) which are fundamental and basic to the task, used by everybody in the profession, and have staying power.
Frameworks on the other hand, are just some code some random guy (or random community) put together. Some are just awfully coded, despite their popularity. They are frequently rewritten. And they get out of fashion every few years.
It's funny you mentioned hammers actually, the movie playing in my head when I was writing that post was of a neophyte hammering nails in all day, struggling to remove nails with some contraption, eventually deciding that there must be a better way to remove nails and inventing the hammer with nail extractor head.
Of course I don't literally mean that; you can write code in a way that makes it easier to debug, extend, etc. But too many developers get wrapped up in engineering the perfect system and forget that they're supposed to be, you know, writing a program. I think this is why a lot of hobbyist projects run out of steam.
Thank you! I asked that for myself and tried to create (really) good code. Result: Hobby project felt more like work, than actual work did. Now I realized why.
At the end of the day, you are either adding value for the company and team or you are not.
> "Working is the lowest bar of quality."
Something that's reached for the most proper implementation, the fastest execution, and the most compatibility with something else is still useless if it produces the wrong results quickly and prettily.
But as I've been adding all the features I originally intended I'm finding it's a bit of a slog. Every new feature I add is pretty well compartmentalized but it all still smells a little + sometimes requires some refactoring to fix unintended side effects. I'm only working on it a few hours a week (as opposed to 16+ last month), partially because it's just not fun writing code that I'm not proud of, but also because new code requires more and more caution as the system grows.
Now that I think of it, the GUI itself was simple enough to do, but the mouse clicks in the 3D scene + various methods of selection were the biggest pain. The GUI just had to show things related to those selections.
Coder heaven is nice. It has free juice, catered lunches, and foos-pong tables. Individual offices, with plenty of collaboration-friendly huddle rooms. You're only on call 1 eon out of every 4. Unfortunately, the universe is one giant CRUD app.
Probably better off not writing perfect code.
When I was a young engineer I used to think, "One day, ONE DAY, the company will go down in flames for all this bad software practice, and then I can stand triumphantly among the ashes gloating over how I was SO RIGHT to worry about compiler warnings!"
It never happens.
When I started coding, I though you could only have one letter variables, like a, b, c, x, y, z. I did not question this, but one day I ran out of variables ...
Edit:
I looked at some of his other posts and saw an altitude bed on an old photo, witch concludes he probably is/was an athlete. I think it's common among athletes to have the mindset that they want to keep improving their skill level. This can be a good trait as a developer, but they are hard to manage, as such persons will quickly outperform their colleges and get bored. They work best with other people like themselves, or with old experienced developers. Make sure you protect him so that he do not burn out himself or his team. While these "10X" developers can work very hard, they are just humans.
At least the minifier wouldn't have to do much work. :)
I credit a lot of my initial understanding of how programming works to making various text-based games on those calculators while only half paying attention to class in high school.
I was very sad when I realized the BASIC performance was like an order of magnitude worse than ASM performance.
No need to be harsh on yourself if you created games like this on that age!
I'm thinking of making the whole game open source but I'm so ashamed of the codebase that I don't want anyone to see it. It's a dilemma since I think the game has potential as an open source project. It's inspired by Ultima Online, Minecraft and Reign of Kings but with a lot of constraints making it easy to implement new features. It also has quite a few dedicated players.
I'm currently in the process of rewriting the front-end from the old jQuery mess to React. It's like 95% feature complete but as soon as that is done I will start investigating what's going on with the mines.
Anyway, here it is: http://canvaslegacy.com/
Again, I strongly advise against starting right now since you won't experience the game like it's supposed to be. It's hard mode even for seasoned players. :)
These two things seem somewhat at odds with each other. Clearly, to players of your game, a fix for this show-stopping bug would offer a fair amount of value, whereas rewriting the frontend, from your description at least, sounds like an exercise that is more for you as the developer.
I'm not criticising, by the way. Just sharing my thoughts based on your comment :)
I tried fixing it initially but eventually gave up and put the whole development on hold for 6 months. Also note that the problem gradually got worse. In the beginning it wasn't such a big deal but eventually became post-apocalyptic when players had a hard time finding even the most basic resources.
Another aspect is the amount of support I had to take care of when the player base was at its peak. It almost made me burn out, consdering that it's a side-project that I'm not making any money of. So when this major bug started affecting the game and the active players began dropping it was almost a relief. I never expected that anyone wanted to play it to begin with. I just put it out there as soon as I had something playable.
So after a long hiatus the joy of rewriting the front-end made me motivated to work on it again. Perhaps not the best strategic move but it feels good to be back. :)
Dear God, I feel like I'm having my game dev life read back to me...
Some random comments follow.
> Still, I loved data binding so much that I built the entire game on top of it. I broke down objects into components and bound their properties together. Things quickly got out of hand.
Boy, you have to see JavaFX. And I inherited a codebase at work written by a cow-orker who was absolutely in love with bindings at that moment...
Also the big blob of code reminded me why good macros in a language (not C-like macros) are a blessing ;).
> Separate behavior and state.
Yeah, learned that same lesson too. I prefer to think in systems operating on data as opposed to a web of objects calling each other. One of the reason is that the web of objects is very implicit; you soon have no idea who actually refers to who anymore.
> If I start typing self. in an IDE, these functions will not show up next to each other in the autocomplete menu.
That's a good and practical point, though I feel dirty about renaming functions for solely that reason. I wonder if this isn't time to experiment with some "first-class editor semantics". Here, ability to explicitly mark functions as grouped together solely for the purpose of IDE displaying them like that in autocomplete and outline view. In my evening Lisping, I'd love to have more control over indentation for macros I write.
> global variables are Bad™
Yeah, that's almost like "goto considered harmful", and about as much correct as a soundbite (i.e. not very). Unfortunately, everyone keeps writing how global variables are evil, and what I'd love to read is some treatment on how to use global variables correctly. For the situations where - like often in games - you absolutely, positively need a lot of globally accessible data.
> Group interdependent code together into cohesive systems to minimize these invisible dependencies. A good way to enforce this is to throw everything related to a system onto its own thread, and force the rest of the code to communicate with it via messaging.
That's a... very self-conscious approach. Odysseus-tied-to-a-mast style.
private int DO_NOT_TOUCH_THIS_IF_YOU_DONT_KNOW_WHAT_YOU_ARE_DOING_Timeout = 7000;
The code actually made it and is still in productionNot quite: Java insists that all (checked) Exceptions be handled or passed up explicitly. One can argue that this design decision is bad, as has been done extensively elsewhere.
However, in the particular example given, I'd argue that it would have made much more sense to display a user-understandable error message to the user (e.g. "Required gun resource file is missing, please re-download the game here: (...)"), and then just System.exit() if it's non-recoverable. Maybe print a stacktrace if the game was started in debug mode.
Everything becomes influenced by the flavour of the week.
Don't be so hard on yourself, We all suck in hindsight, but its all about recognising it an constant improvement.
This is legit af
yesssss
I say, write bad code if it will get you closer to your goal (here, making a game people will pay money to play). Learn from your mistakes, and make new mistakes next time.
http://static.kidspot.com.au/cm_assets/32032/battleship-game...
I.e. turn-based and probably doable with an UI toolkit (as opposed to drawing stuff directly with DirectX / OpenGL)?
Anyway, shoot me an e-mail (address in my profile), I'll give you a few quick hints to get you started.
This year marks 20 years since opening up QBasic as a 13 y/o.
for (int i = this.bindings.Count - 1; i >= 0; i = Math.Min(this.bindings.Count - 1, i - 1))
Why isn't the last expression a normal i--?