• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
tom_mai78101

Poll: There's a big piece of code in need of a rewrite, do you create a new file and work from there, or refactor old code in old file?


20 posts in this topic

I am about to do a code rewrite, but I'm not sure how an expert programmer does it. I would like to follow any sort of conventions to rewriting codes, if there exists any, and hopefully know how to do such tasks with confidence. It's not lanuage-specific, I'm just asking generally.

So, I put up a poll so as to narrow down some of the actions done to do a rewrite. Thanks for polling.

[b]Update[/b]: There's a follow-up. [url="http://www.gamedev.net/topic/632226-poll-theres-a-big-piece-of-code-in-need-of-a-rewrite-do-you-create-a-new-file-and-work-from-there-or-refactor-old-code-in-old-file/page__view__findpost__p__4988644"]link.[/url] Edited by tom_mai78101
0

Share this post


Link to post
Share on other sites
I don't know of any actual conventions to rewriting code as rewriting is a situation you want to avoid in most of the cases, unless you're actually doing a general update of an application.

Personally I try not to break compatibility with the earlier version of the system when rewriting larges systems. An actual rewrite for me mostly starts out on paper by fleshing out what the system is supposed to do and how it achieves its goal right now. Then I flesh out the new approach I want to use in detail so the actual implementation becomes quite trivial. Depending on the system I either create a separate branch of the project where I completely replace the old system with the new one, or I create 2 parallel code paths with both the old and the new system in place (if possible).
When that's done you can start adapting the rest of the project to this system if needed. Once the new system has been properly tested you can get rid of the old one.

This is for larger complex systems of course, if it's a small rewrite I would just do it in place providing you have backups of the old code so you can revert to that if something goes wrong.
1

Share this post


Link to post
Share on other sites
From my very limited experience i can say that if a piece of code is a mess, you should just rewrite it or else the new one will still have a messy large scale structure.
0

Share this post


Link to post
Share on other sites
Either way is fine, it just depends on how you go about the re-factoring Sometimes it is nice to create a new file so you can keep the old one open for reference. If you decide to just rewrite the file without creating a new one just make sure you have a backup (if you are using a version control system you are good to go).
0

Share this post


Link to post
Share on other sites
[quote name='tom_mai78101' timestamp='1349276504' post='4986408']
I am about to do a code rewrite, but I'm not sure how an expert programmer does it. I would like to follow any sort of conventions to rewriting codes, if there exists any, and hopefully know how to do such tasks with confidence. It's not lanuage-specific, I'm just asking generally.

So, I put up a poll so as to narrow down some of the actions done to do a rewrite. Thanks for polling.
[/quote]

1. Why am I rewriting the code? If the software works and there are no changes needed, then leave it alone.
2. If I have to make a minor tweak to the software, then I'll try to find it in the existing code base (costs less time).
3. If I have to make major changes to the code, then I treat it as a new project/version and go through the software development lifecycle. If the code base is poorly formatted, poorly commented, poorly architected, then I'm very tempted to just start from scratch. However, it really depends on my personal assessment of what would take the least amount of time.
4. If I have to rewrite the code from scratch, I will use the existing software and code as a source for eliciting requirements and business rules.
0

Share this post


Link to post
Share on other sites
First off I need to know why I am touching it.

Since I have version control in place, I know I can always back out my changes if necessary, so there are no qualms about working in place.

Never touch working code. If it already works, then any changes are bound to make it worse.

If I am fixing a bug, I want to touch as little of the file as possible to fix the bug.

If I am adding a feature, I will perform whatever automated refactorings I can to preserve behavior and cleaning it up. That means moving functions around, extracting or merging functions as necessary, commenting, and doing whatever else I need to get a solid understanding of the code. Once I understand it, I will make minimal functional changes to meet the requirements.

The only other reason I can think of to touch the code is for performance. In that case, after doing the necessary steps to understand the code (see above), take new accurate timing measurements, comment out the low-performing section, write (in place) the code I believe will perform better, and take a second set of timing measurements. After repeating a few times, and the new code meets the required metrics, I'll optionally remove the commented out original --- although sometimes it makes sense to leave it in so people understand the optimized version --- and submit that.
1

Share this post


Link to post
Share on other sites
It depends.

Does the interface need to remain, or is that being changed?
What percentage of the code file is changing?
Is it one code file or many?
Do I need to test the results of the refactor vs the existing version?
What language am I working in (some languages make including the new file onerous)?
What's the risk if I screw up the refactor?
How difficult is the refactor?
Am I working in source control?
1

Share this post


Link to post
Share on other sites
[url="http://www.joelonsoftware.com/articles/fog0000000069.html"]Never rewrite from scratch[/url].

If you do need to refactor code, first make sure the existing code is adequately tested. The level of testing will depend on the criticality of the code. Get the unit tests into a good shape. Then [i]carefully[/i] refactor the existing code, noting any breakages to the tests.
1

Share this post


Link to post
Share on other sites
All the code is in version control.

If your code is in version control, and regularly committed each time you have stable, working code, then you don't have to worry about losing code, or whether you'll wreck things irretrievably - If you do, simply revert.

If it's not in version control, it doesn't exist.

Code that's not in version control is your theory on what might make the code better. But until it's tested, passed quality checks and committed, it's just that - A theory.

If it's not in offsite backup, it could vanish at any time.

Your code should be stored in at least three places. These are three possibilities:

1) In your local working copy.
2) In your local RAID array or backup hard-drives. Note the plural.
3) In offsite backup. (I use two of these)
0

Share this post


Link to post
Share on other sites
As others have said, it depends.

If it's a clean up then in place.
It it's a top down performance rewrite (such as C++ => intrinsic based vectored code) then depending on the size either in place or I'll copy the old code out to notepad++ on another monitor and replace.

If it's a self contained function then I'll keep the old function and write a new one with a name which indicates the difference and direct the code there (such as a recent 'calculate SHParameters' which became 'calculateSHParametersSIMD' once I rebuilt it.
1

Share this post


Link to post
Share on other sites
[quote name='ChaosEngine' timestamp='1349294778' post='4986514']
[url="http://www.joelonsoftware.com/articles/fog0000000069.html"]Never rewrite from scratch[/url].

If you do need to refactor code, first make sure the existing code is adequately tested. The level of testing will depend on the criticality of the code. Get the unit tests into a good shape. Then [i]carefully[/i] refactor the existing code, noting any breakages to the tests.
[/quote]
You shouldn't rewrite [i]the entire project[/i] from scratch, but it's perfectly acceptable to re-write a function or class from scratch, as long as you can get it working fully within a reasonable time-frame (48 hours or less seems like a reasonable number to toss out). The larger the chunk of code you are rewriting, the greater you'll underestimate the work involved, and the further you'll dig yourself into a hole.

On the other hand, the more you patch something instead of rewriting it, the messier it becomes (unless you refactor - which you should). It has always seemed more beneficial to me to re-write functions or small classes from scratch, but patch larger classes and projects in-place (and then refactor to clean any mess from patches, or else patch cleanly in the first place).

Similar to phantom's method, if I have MyFunction(), I'd write alongside it a new version: MyFunction_new(). Once written and tested, I'd delete 'MyFunction()', and rename 'MyFunction_new()' to drop the '_new' part of the name - this way I still have the old version right there to read while coding the new version, and the program still compiles file while I'm working, using the old version until I'm ready to make the swap.
1

Share this post


Link to post
Share on other sites
Like other posters I first make sure the code is checked into source control. Then I copy the code and paste it back into the same file but put the whole thing in a comment block. This is my reference. Then I go through each block of code and refactor it. If I need to re-check the original functionality, its sitting right there in the file commented out. If I really screw it up I can always go back to the version in source control.

If it's a really complicated function I'll often refactor the first part then test and debug that then continue with the refactoring.

Another thing I like to do I call pre-factoring. This is where I make non-breaking changes to the code that will make the refactoring easier, but the code still compiles and works.
0

Share this post


Link to post
Share on other sites
As a previous poster mentioned, unit tests. Make sure every output of the code to re-write has unit tests, including edge cases. Then you have a target to aim for, e.g. your new code passes those same unit tests. Keep the old version around in a separate class so you can add new unit tests and compare outputs if you have any questions.

Throwing away old code is a double-edged sword. If you just refactor and refactor you may be tied to an underlying structural flaw. If you go from scratch, you can lose implicit business rules.
0

Share this post


Link to post
Share on other sites
Wish there was an "all of the above" options because it really depends on the situation. For instance, here are some general rules I go by:

1) Was I on the right track? Is there something here worth saving? Was this a good idea, but it just didn't turn out the way I wanted? If so, I will re-factor within the file.
2) This code is complete garbage. It can't be saved. It's crap and needs to be annihilated. If so, I will start in a new file.
3) There are parts that are exactly as I want them, and others that just need to be thrown in the trash. If so, i may use some copy/paste.

Just my two cents.

[quote]Throwing away old code is a double-edged sword.[/quote]

If you use version control, there is no such thing as throwing away old code =) You can always go back and see if the way you had it before was better, or roll back to another point where things were better before you started messing around. Edited by metsfan
0

Share this post


Link to post
Share on other sites
If it's really big I would probably create a branch specifically for that refactor job.

Then I would just do whatever I needed to refactor what needs to be refactored and merge the branch back in when I'm done.

I chose other, as I am doing copy-pasting but I am also editing the file (just in another branch). I always get a little bit anxious \ scared when I refactor large amounts of code, it always works out when I test though :P.
1

Share this post


Link to post
Share on other sites
[b]This is a follow-up.[/b]

Very recently, a friend of mine was curious on my project, and asked if she may view my code. Since she's kind of hot, I could not turn down such an offer. Brought out my laptop, turn it on, 5 minutes later, and I have my IDE displaying my codes to her. She glanced at them, and expressed befuzzlement at so many functions with the same name, different parameters, all inside a class.

I admit to her gullibly stating that those functions do specific tasks on different entities a game object may encounter throughout the game. After somewhat of a pep talk and chit-chat, she left, while I was having butterflies in my stomach and many second thoughts.

I looked over my codes, and realized it's really ugly. There are tons of codes overlapping one another, and places with the same logic in some of the functions. The more I look at it, the more it transforms into C-like and not Java-like, even though it's written in Java. And I probably am not good looking if my codes are also not good looking.

Should I consider myself a rewrite, even though the codes and the logic all function perfectly? There are thousands of codes written in "procedural Java" throughout the entire project, and this could take weeks... Edited by tom_mai78101
0

Share this post


Link to post
Share on other sites
[quote name='tom_mai78101' timestamp='1349858026' post='4988644']
Very recently, a friend of mine was curious on my project, and asked if she may view my code. Since she's kind of hot, I could not turn down such an offer. Brought out my laptop, turn it on, 5 minutes later, and I have my IDE displaying my codes to her. She glanced at them, and expressed befuzzlement at so many functions with the same name, different parameters, all inside a class.

I admit to her gullibly stating that those functions do specific tasks on different entities a game object may encounter throughout the game. After somewhat of a pep talk and chit-chat, she left, while I was having butterflies in my stomach and many second thoughts.
[/quote]
Lol, a hot female developer, haven't seen one of those in a while [img]http://public.gamedev.net//public/style_emoticons/default/smile.png[/img]

[quote name='tom_mai78101' timestamp='1349858026' post='4988644']
I looked over my codes, and realized it's really ugly. There are tons of codes overlapping one another, and places with the same logic in some of the functions. The more I look at it, the more it transforms into C-like and not Java-like, even though it's written in Java. And I probably am not good looking if my codes are also not good looking.

Should I consider myself a rewrite, even though the codes and the logic all function perfectly? There are thousands of codes written in "procedural Java" throughout the entire project, and this could take weeks...
[/quote]
I would do it bit by bit. It does sound intimidating when you have a 30k line monolith that you've been adding to for the past two months and need to clean it up, but you need to do it until it reaches critical mass and becomes impossible to maintain. Do it slowly - find any repeated code, move it into a separate function. Divide your code into classes where it makes sense, and don't worry about performance. Delete any performance hacks you had before, you can always put them back in later, for now the code needs to be readable so you know where you are at. Comment a lot, but don't waste your time doing that. If you have unit tests, a good time to use them is every time you make a refactoring change (provided they don't take forever), this way you won't accidentally break code.

Eventually you are bound to encounter a design flaw, a situation where your old code cannot neatly be refactored in a different form and needs to be rewritten more or less from scratch, but this kind of code is typically interface code which should only consist of a few method calls. Most of the complex code should be self-contained. Edited by Bacterius
0

Share this post


Link to post
Share on other sites
Understood. Just tried to move a tiny chunk of repeating codes into a function. Just that alone costs me 30 minutes to copy/pasting and Ctrl+Fing around for 4 lines of repeating codes. I can see it now, me spraying some deodorant.
0

Share this post


Link to post
Share on other sites
I like to add technical debt to the discussion.

You try to add a feature and find the place where other related features exist. If these features are put to the wrong class (or wrong library even) in the first place, it easily creates unneeded, circular or two-way dependencies. Maybe the right class (or library even) for these features doesn't even exist. There exists some technical debt there. Least time consuming, and most short sighted way is to add it where related features are, even if they are design wise in the wrong place. This adds technical debt. You need to assess if the debt is justified. Too much in early project cycle and it becomes unmaintable mess, while at the end of the project it's usually ok.

Need to refactor usually rises from the violation of single responsibility rule. Find out the responsibilities of the class, and you can usually cleanly separate them.
0

Share this post


Link to post
Share on other sites
I agree with what CRYP7IK and Radikalizm said, consider using a branch. If you are not using version control, then start with that first thing you do. I got the feeling you are not, as this is not included as one of the options of the poll.

A branch could be problematic to merge if you do a lot of changes everywhere. But from the question, it looks like the problem is "local".
0

Share this post


Link to post
Share on other sites
[quote name='CRYP7IK' timestamp='1349401989' post='4986984']
If it's really big I would probably create a branch specifically for that refactor job.
[/quote]

At work I make a point of having two active branches I can swap between at will; when combined with Perforce's 'shelve' feature it makes working on large changes pretty simple.
0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0