The evolution of code

I’m wondering what’s the best way to write good, maintainable, logical code that evolves and adapts as your needs change.

For instance, right now I’m developing a multiplayer game built off JBox2D, but the code originally started off as just a way to see if I could save/load JBox2D Worlds. I showed the program to a few friends and they got excited about the physics and proceeded to generate a lot of good ideas for games that could be created out of it. So I’ve been adding this bit and that bit; right now I’ve got two-player synchronization and a few game mechanics in, but I’m running into problems with attaching game specific data onto the World (I’ve been using a Map<String, String> as my UserData that gets serialized with the Body). Long story short I’m now finding myself re-writing serialization code for my own application-specific classes. It would be much easier to have written wrapper classes for World and Body (and make them implement Serializable) to begin with, but of course at the beginning I didn’t know what direction the program was going to take.

That tends to happen with programs – the more you write code, the more you realize that you need to completely rewrite the code. Is there no other way? One could plan ahead and design classes and abstractions from the beginning to alleviate some of the necessity to re-write code, but sooner or later I always find myself doing a complete overhaul of this part or that part (or every part) of the code. The basic problem is that you never know what direction a project will go in; you can steer it but there will always be new things that pop up – new features, overlooked problems, a change in concept, etc. Is the only solution to overhaul the internal mechanics, again and again? You could possibly write a lot of abstraction barriers to begin with but in general any kind of decision may need to be changed.