Jump to content

  • Log In with Google      Sign In   
  • Create Account

We're offering banner ads on our site from just $5!

1. Details HERE. 2. GDNet+ Subscriptions HERE. 3. Ad upload HERE.


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?


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
20 replies to this topic

Poll: Code Rewrite (38 member(s) have cast votes)

A large piece of code requires a rewrite, where do you start?

  1. Create blank file, and start from there. (12 votes [31.58%] - View)

    Percentage of vote: 31.58%

  2. Refactor code inside original file. (18 votes [47.37%] - View)

    Percentage of vote: 47.37%

  3. Do some copy/pasta, baby! (3 votes [7.89%] - View)

    Percentage of vote: 7.89%

  4. Other. (5 votes [13.16%] - View)

    Percentage of vote: 13.16%

Vote Guests cannot vote

#1 tom_mai78101   Members   -  Reputation: 577

Like
0Likes
Like

Posted 03 October 2012 - 09:01 AM

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.

Update: There's a follow-up. link.

Edited by tom_mai78101, 10 October 2012 - 02:35 AM.


Sponsor:

#2 Radikalizm   Crossbones+   -  Reputation: 2974

Like
1Likes
Like

Posted 03 October 2012 - 09:14 AM

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.

I gets all your texture budgets!


#3 Waterlimon   Crossbones+   -  Reputation: 2634

Like
0Likes
Like

Posted 03 October 2012 - 10:08 AM

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.

o3o


#4 BrokenKingpin   Members   -  Reputation: 228

Like
0Likes
Like

Posted 03 October 2012 - 10:25 AM

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).
Do you folks like coffee?

#5 slayemin   Members   -  Reputation: 2896

Like
0Likes
Like

Posted 03 October 2012 - 10:28 AM

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.


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.

Eric Nevala

Indie Developer | Dev blog


#6 frob   Moderators   -  Reputation: 22692

Like
1Likes
Like

Posted 03 October 2012 - 10:49 AM

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.

Check out my book, Game Development with Unity, aimed at beginners who want to build fun games fast.

Also check out my personal website at bryanwagstaff.com, where I write about assorted stuff.


#7 Telastyn   Crossbones+   -  Reputation: 3730

Like
1Likes
Like

Posted 03 October 2012 - 11:40 AM

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?

#8 ChaosEngine   Crossbones+   -  Reputation: 2499

Like
1Likes
Like

Posted 03 October 2012 - 02:06 PM

Never rewrite from scratch.

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 carefully refactor the existing code, noting any breakages to the tests.
if you think programming is like sex, you probably haven't done much of either.-------------- - capn_midnight

#9 Narf the Mouse   Members   -  Reputation: 318

Like
0Likes
Like

Posted 03 October 2012 - 02:31 PM

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)

#10 phantom   Moderators   -  Reputation: 7555

Like
1Likes
Like

Posted 03 October 2012 - 03:00 PM

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.

#11 Servant of the Lord   Crossbones+   -  Reputation: 20948

Like
1Likes
Like

Posted 03 October 2012 - 03:10 PM

Never rewrite from scratch.

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 carefully refactor the existing code, noting any breakages to the tests.

You shouldn't rewrite the entire project 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.
It's perfectly fine to abbreviate my username to 'Servant' rather than copy+pasting it all the time.
All glory be to the Man at the right hand... On David's throne the King will reign, and the Government will rest upon His shoulders. All the earth will see the salvation of God.
Of Stranger Flames - [indie turn-based rpg set in a para-historical French colony] | Indie RPG development journal

[Fly with me on Twitter] [Google+] [My broken website]

[Need web hosting? I personally like A Small Orange]


#12 Postie   Members   -  Reputation: 1116

Like
0Likes
Like

Posted 03 October 2012 - 04:51 PM

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.
Currently working on an open world survival RPG - For info check out my Development blog: ByteWrangler

#13 jefferytitan   Crossbones+   -  Reputation: 2242

Like
0Likes
Like

Posted 03 October 2012 - 05:05 PM

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.

#14 metsfan   Members   -  Reputation: 654

Like
0Likes
Like

Posted 04 October 2012 - 07:14 PM

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.

Throwing away old code is a double-edged sword.


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, 04 October 2012 - 07:15 PM.


#15 CRYP7IK   Members   -  Reputation: 1011

Like
1Likes
Like

Posted 04 October 2012 - 07:53 PM

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.
To accomplish great things we must first dream, then visualize, then plan...believe... act! - Alfred A. Montapert
Gold Coast Studio Manager, Lead Programmer and IT Admin at Valhalla Studios Bifrost.

#16 tom_mai78101   Members   -  Reputation: 577

Like
0Likes
Like

Posted 10 October 2012 - 02:33 AM

This is a follow-up.

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, 10 October 2012 - 02:40 AM.


#17 Bacterius   Crossbones+   -  Reputation: 9262

Like
0Likes
Like

Posted 10 October 2012 - 06:22 AM

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.

Lol, a hot female developer, haven't seen one of those in a while Posted Image

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...

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, 10 October 2012 - 06:22 AM.

The slowsort algorithm is a perfect illustration of the multiply and surrender paradigm, which is perhaps the single most important paradigm in the development of reluctant algorithms. The basic multiply and surrender strategy consists in replacing the problem at hand by two or more subproblems, each slightly simpler than the original, and continue multiplying subproblems and subsubproblems recursively in this fashion as long as possible. At some point the subproblems will all become so simple that their solution can no longer be postponed, and we will have to surrender. Experience shows that, in most cases, by the time this point is reached the total work will be substantially higher than what could have been wasted by a more direct approach.

 

- Pessimal Algorithms and Simplexity Analysis


#18 tom_mai78101   Members   -  Reputation: 577

Like
0Likes
Like

Posted 10 October 2012 - 12:42 PM

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.

#19 Codarki   Members   -  Reputation: 462

Like
0Likes
Like

Posted 12 October 2012 - 10:50 AM

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.

#20 larspensjo   Members   -  Reputation: 1557

Like
0Likes
Like

Posted 14 October 2012 - 01:57 PM

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".
Current project: Ephenation.
Sharing OpenGL experiences: http://ephenationopengl.blogspot.com/




Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS