Archive for August, 2009

Legos and Optimization

Sunday, August 16th, 2009

Everyone wants faster, simpler code.  “Optimization” doesn’t mean the same thing to everyone though.  For example a FSM.  This usually start out as a big mass of very simple states.  You then “optimize” redundant and nop states away, and combine states.  For example a simple FSM for most console games

Logos -> Loading screen -> Main menu -> ….

After main menu, you could go to any number of states such as playing the game, loading a save, configuration, etc…  The first three states though, will always follow the same path and can be combined down into one state.  This is great on paper and pencil because now you have less things to draw.  When translating this into the software world each “state” can be represented as its own object or method.  So we’ve also cut down on the typing we had to do in software.  Such an “optimization” was probably not a good thing though.   If the code has to change later we’ll have to break apart the state to put in a new state.

It’s best to leave the states as separate states (objects,methods) in the software.  This allows the code to easily be changed later if and when it does (because it will always change).  By having objects/methods do TOO much, it has a level of complexity that does not and should not be there.  Break things up into smaller, simpler parts.  Maybe you have already heard of Cyclomatic complexity (Firefox hasn’t though, as it comes up as a spelling error.)  There are a number of tools on the web that will measure the this on each method/class in program.

If the three initial states were merged we’d end up with one state that was 3x more complex than the individual states.  In terms of maintainability, this isn’t a good thing.  Merging the states also did not make anything faster, and might have made things slower.  Instead of the state machine deciding which of the three states we are in, the new ‘optimized’ state much decide which of the three states it is in, so there are two decision points instead of one.

Having lots of small methods, classes,objects in a program is not a bad thing.  Merging them down into larger objects is not a good thing.  Keep the code broken up as possible, or it will become unmaintainable mess of large objects with very specific (and sometimes redundant) functions .   Think of code like building blocks.  As long as the objects are small you can mix and match them anywhere to build things.  The larger pieces can only be used for a few things and are limited in their use.  Look at some of the Lego sets you can buy.  Some are made with very generic parts that can be used for almost anything.  Others have very specific (often large) pieces that serve specific functions.  Such as a cockpit on the spaceship, or a fancy roof for a building.