Code refactoring in videogames


What is actually to refactor?


—Joshua Kerievsky, Refactoring to Patterns
[quote taken from wikipedia]


Typical examples, usually supported by IDEs, are extracting repeated parts of code from different places, to create a function that can be reused. Or changing the parameters of a function so it can be a little more generic and also reused better. But those are code-level examples of refactoring, and in a general way, refactoring means changing your code to be better. And “better” should be understood as better to “handle the problem it is intended to handle”. So it might happen that the code you wrote at the beginning was just some prototype code and you need to make it more understandable or usable, or that your understanding of the problem at hand has changed, and so the code is no longer good at handling your new conception of the problem.

So of course It makes sense to change bad, rushed code and turn it into something readable, and that should be done as quick as you can, before you forget what that constant meant, or why you do things in a particular order. But after a while, your code stabilizes becomes robust, and it is not so important to touch it again. So how about when your problem changes?

Reinventing the camera, or parts of it

I remember discussions more than 10 years ago with fellow developers about how “Making videogames is like filming a movie but having to develop a new camera for every time”. Nowadays that is not so true, as component based game frameworks (like Unity) allow you not only to reuse the engine, but also parts of functionality, as long as you developed them carefully.

So the “base technology” part of the problem to solve, is not part of what you need to refactor. In a game, the other big part is the game logic itself. And usually, you just develop the game once, on a strict budget and with little time, you release it, maybe you patch it, and never really touch the code again. So… why refactor the dialog system?

Refactoring is also learning

Because, stretching the term a bit, sometimes what you refactor is your understanding of a particular problem. Sometimes you have to redo things to understand on an abstract level what a good solution would be. Because the only thing that you will carry for certain from a project to another, is your understanding on how to solve problems. In my case, the dialog system is a mess. I have several dialogs across the application, each made in a custom way, and I’m having to add a lot of ad-hoc logic to deal with the purchases (showing a dialog, waiting, closing it when another messages comes, etc.). And even though I might never touch this again, I need to learn how to solve this problem with my current tools, so in the next game I will be more efficient. Because if I don’t learn now, anyway I will have to deal with this problem in the future. And doing it the right way from now onward, is much more efficient than doing it wrong forever.