Programming “constructor spaghetti” – it’s not yummy!

When you are in a Big Huge Hurry to finish a project (like I am now), and you are building new classes, here’s a simple bit of advice that isn’t easy to follow: keep your constructor parameters minimal. If you don’t, things could end up getting insane fast.

All the trouble begins, of course, when you’re programming at 90 miles per hour and what looks to be the quickest way to do something ends up being a bad way to do it. In my case, I was giving some constructors too much data all at once. I was sending stuff to be initialized that should have been deferred and separated into other functions.

For example, tile layers were being given view constructs (like the view camera). It’s clear to me now, after I’ve been forced to re-examine it, that assigning the camera reference at the constructor not only 1) forces a dependency on the constructor which limits how I can use it, but 2) it isn’t really useful at that point anyway, and 3) it’s plain bad design! If I just stick to good principles of software architecture, I would have realized right away that this is destroying class cohesion and I’m only on the constructor function! What’s going to happen to the other member functions?

(In reality, it’s not that simple. These additional parameters were added over time as things grew and got more complex, incrementally. But that’s even more reason to be mindful of this issue!)

So instead, I took that out and added an attachCamera() function. Now I’m more free to construct the tile layer in various places (there are different initialization sequences/environments in the game and in the editor, so this became a problem). But also it’s better design, because my constructor should only ever receive parameters that are critical to the creation of the class instance. To finish with the example, a tile layer doesn’t need to know what camera it’s using when it’s first created because it’s not even in a tile map yet. Duh.

But this stuff is easy to forget when you’ve been going for 12 or 14 hours. Had I not needed the editor use case, I might have not realized the damage I was doing so I could undo it now rather than later. *whew*

Leave a Reply