What Are the Unwritten Rules of Deleting Code?
Press2ToContinue writes "I came across this page that asks the question, 'what are the unwritten rules of deleting code?' It made me realize that I have seen no references to generally-accepted best-practice documents regarding code modification, deletion, or rewrites. I would imagine Slashdot's have come across them if they exist. The answers may be somewhat language-dependent, but what best practices do Slashdot's use when they modify production code?"
one unwrite that has which been deleted?
The more you can delete, the better.
"First they came for the slanderers and i said nothing."
Delete away! It's not like legacy versions aren't available. Most code should be deleted. Almost all production code is bad.
Help stamp out iliturcy.
what best practices do /.'s use when they modify production code?"
Should be able to easily revertable
I really like git, but the key thing is to keep revision history. Deleted code is then never "deleted" it's just no longer cluttering up the screen. Of course it does mean you need to actually learn how to use a version control system beyond blind forward checkins.
This is a boring sig
3 days ago.
Delete it, and hope to god you didn't just break something.
Who cares? You've got source control (SC) right? And you write unit tests right? If so then new code will pass the tests. If you write some benchmarks on performance then you'll know that too.
Build early, build often, build against test coverage and you've got Continuous Integration (CI). If you've got CI and SC then anyone can write new code and it will either pass the tests or it will break the build. If it breaks the build use SC to pull that crap out.
Done and done.
A fool throws a stone into a well and a thousand sages can not remove it.
Let Vigil delete your code for you when it's wrong and must be punished.
It's often good to just delete. Sometimes however I feel the need to put in a comment reminding the reader that the old functionality is gone. For example, it could say "no need to support device X here" or "input has already been validated". That's because it's not always evident to look in source code history to notice that there used to be something there.
Don't necessarily agree with this, but we comment out all older code when diffs aren't used. Commented code blocks with the date and editor's name works for small projects on a very tight deadline and this makes things easier if we want to rollback. Bigger projects do use diffs.
As always, this is going to be a case of "works best for my situation", rather than just "best" method to do xyz.
From the article:
Since I work on contract, I don't renew if management has a chronic unawareness problem and more often than not, the problem is people. Clueless hierarchies are a symptom of a bigger disease, the brunt of which, I'd rather not take onto my shoulders.
If computers were people, I'd be a misanthrope.
A link to a discussion on another site that was itself a link to a discussion on another site.
I know it's easy stories, but really? Are the slashdot trolls really going to offer any unique and useful insights that Ars and Stack Overflow haven't already covered?
#1 Make sure your code is better. ... Don't get caught!
#2 If it isn't
If I posted them here, they'd be written rules. If you'd like to talk with me about them, you might be able to reach me at: 0118 999 881 999 119 7253
Seriously, it's called refactoring. If you've never heard of it you really need to learn more about your craft. There are lots of books on it. Just saying you want to modify production code instead of releasing a new version says a lot about your development skills or that I read too much into people's questions.
Unused code gets deleted no exceptions. If there's no client demonstrating its value, its value is zero. The reasons are obvious in systems that scale into the hundreds of thousands to millions of lines of code.The way I describe it to my teams is, Just-In-Time development rather than Just-In-Case. You can have a conceptual framework in place and fill it in on demand without committing yourself to an orthogonal matrix of features that 'might be useful'.
Read the book Clean Code by Robert C. Martin aka uncle Bob.
and then watch the videos at http://www.cleancoders.com/
Ok so you are working on a team and deleting code. Here are some basic rules to follow.
1) Don't delete your boss's code. Just change all the function calls to go around it. If he asks you about it, say that someone else changed it.
2) Don't cuss out the guy who's code you are deleting until after you are done. You might have to ask him why he did certain things (unexpected library behavior etc).
3) Make sure the code you add to replace the old code is longer than what you deleted. That way, you can tell your boss that you added 'x' lines of code to the project.
4) Don't waste time unit testing your new code. Obviously if you have to replace the old code, then you are a better programmer than the last one. If the last programmer's code passed unit tests, and you are better, then obviously yours would pass unit tests too.
Any politeness the other programmer shows to you after you delete his code is not to be trusted. The code we write is pride to us, and deleting someone else's code is like seeing your coworkers girlfriend naked in the shower. Sure, it's not really your fault and you didn't really do anything bad. But expect some negative passive aggressive behavior in response.
I am paid by the line, I NEVER delete.
Check your test suite covers all the functionality you want your program to have. If you're feeling paranoid, create a couple of tests that WILL fail when the undesirable code is deleted. Make sure everything is in the repo. Maybe branch/tag. Delete, repeat tests, roll-back or checkin (after deleting the canary tests added above) and move on to the next thrilling episode in your coding career.
The first sentence of the paragraph above is of cours the killer - without a full-stack suite of tests there'll always be room for doubt.
Many places have standards for deletion of code, this is of course assuming by deletion you mean completed gone not just archived in source control. Deleting old code is like deleting history, if it is not there to learn from you are destined to eventually repeat the same mistakes. We never delete code that has been live and in production, comment it out or archive it off in source control, nothing that made it through to a live system is ever under any circumstances deleted.
1) Just delete it (do NOT comment it out)
2) Put the reason in the check-in notes
Any decent version control system + sensible test suites will take care of the rest.
Personally I can't stand it when people just comment out code. Either it is needed or not. Don't clutter up code files with useless junk...it will come back to hunt you, even in small projects.
There used to be written rules for deleting code. Then someone deleted them. And since we don't use version control, we have no way to get them back.
Please correct me if I got my facts wrong.
Apparantly my last post got deleted or somehow dissapeared:-(
Code refactoring is well described in the book Clean Code written by Robert C. Martin AKA Uncle Bob.
The Book contains some good examples on how to rewrite legacy code with a few wll picked hands-on examples.
He explains a multitude of "rules" for modifying and deleting code, as well as testing it.
If you want to remember his rules it is a good idea to pay for and watch the videos at http://www.cleancoders.com but it is not necessary.
...I just keep deleting code until the program runs faster! When the boss sees the performance figures go up, that's tangible progress you can take pride in!
In any case, just delete lines of code at random until you observe malfunctions. If eliminating a line of code has no apparent effect, the code must be superfluous!
Programs like SVN, TFS from Microsoft and GIT take care of remembering all the changes, of course. That's what I do for a living. With software change management using these programs, you can write any documentation you want as you can access any part of the code at any moment in time in its history. At my place of work, we are using the Scrum development process and past code isn't really worried about too much. In a sense we are always massaging all the code in the direction of satisfying clients, and making the code work better, while keeping track, using TFS of all the described items that were worked on as time goes along. We can access any file at any time along with its associated work items. From this any sort of story can be created about the deletion of code. The usual story in a busy business is that documentation is hard, so let's just move on.
Delete whatever you want behind a well-defined API barrier, as long as it still does the job when you're done.
Delete entire unused and obsolete APIs where appropriate.
Individual function bodies count as APIs, as well as large modules.
Once the developer has left the organisation, then you delete all their code.
Use version control and do your changes on development code.
Either you use VCS, and you can' t ever delete code because you use it properly. Then the answer is: You can delete whatever you like in the latest revision. If you don't use VCS you have problems that exceed the scope of deleted unused code by a factor 1000, and you shouldn't be allowed access to ANY production code.
No.
1. Don't delete anything, just comment out things
2. Delete everything EXCEPT var_dumps etc (make sure the code works)
3. Write a description in comments for functions / weird crap. Delete all unused code, indent with 2 spaces.
at least if you make the code look visually nice, people think you know what you're doing.
I do PHP, sorry purists.
I'm not signing anything
And just as hard to make it permanent ....
... for clarity
1. mark it as deprecated (although not every language has this option) so that nobody starts adding new calls to it
2. find any place it is used and find workarounds/replacements
3. comment it
4. After a reasonable amount of time if nobody complains that it's been commented, delete it
5. (D)VCS is your friend to revert any of the above.
Points 6. and 7. are left to the imagination (lack thereof) of other ACs and FTFYs ...
It really depends on the code itself.
But generally, if the code is still useful as a guide or reminder, I'll comment it out, and then gradually delete the comment blocks as they lost their usefulness.
If the code's useless from the get go, I'll just nuke it with holy hellfire without blinking.
Captcha: discreet
...on these unwritten rules, they'd have been written down a long time ago.
systemd is Roko's Basilisk.
At a previous employer, there was a *written* rule for deleting significant blocks of code.
If a properly functioning block of code already in production was being deleted due to changes in business requirements, a comment should be inserted at or near the point of deletion, which mentions that some code was deleted and the original code can be found in version x.xx, and preferably a phrase saying what it did.
However, if the code was not yet released to the production system, or was being deleted because it's buggy, it was acceptable to simply delete it without leaving a comment (if somebody needed to research an old bug they could look in the bug tracker, which would show which version of the code last had the bug, so there was no need to mention the bug-deletion in the code).
---------
There is inferior bacteria on the interior of your posterior.
most of the time I want to delete old code when I've written something newer to replace it. I keep the old code there for easy reference, until I'm confident the new code works at least as reliably as the old one.
1) Adding new code is always ok. Just need to keep it independent of the old code. Avoid modifying intersection of old code and new code.
2) Modifying code is dangerous. It can break features anywhere in the system.
3) Deleting code is extreamly dangerous. It can both break code, and lose information what was original code version.
No amount of version control hacks is changing these rules.
The first rule of code reuse is - the code must be worth reusing.
If you're not sure, put it in a fucking SCM & delete away.
We have quite approx 20 people in our team that can be working on various things from VB Code, SQL Statements, router configs, anything text based that can be modified. We have been using ngsource for some years now and its worked very well for us http://www.ngsource.com/SourceControl.htm I'd suggest using this for the basics of version control, etc.
While RCS may be well and good, it won't necessarily show what was deleted or why.
My rule of thumb is to comment out the old stuff, and date it. If it is still there after a few months and the new stuff has been working without anyone noticing or commenting (in a negative fashion), this it's pretty safe to delete it and leave any history/archiving to RCS. Before doing the final delete, I will usually still put a comment in the function/proc header (if I hadn't already done so) about the deletion/major-change as this is more often than not the only thing that is really seen.
If you're operating on a more basic level, clone the crufty code, put the cruft in comments explaining CLEARLY why you cut it out.
When you fix or replace what you cloned, comment there as to exactly what you think was wrong or broken, and how you fixed it.
One thing that is certain, with production code, you will NOT be the last person to work on it. Pay it forward with good practice.
Red
Personally I use the "Back Space" key but I have heard of strange perverted creatures who use the "Del" key :)
Build a Man a Fire, and He'll Be Warm for a Day. Set a Man on Fire, and He'll Be Warm for the Rest of His Life.
The more you can delete, the better.
Starting from the Murphy's law on programming: Every non trivial program has at least one bug
You can derive by rigorous analogy the Murphy's law on not-programming: Every non written code has exactly zero bugs
I have it - the holy grail, the key to bug free coding. If the deleted code has no bugs just restore the deleted lines and delete the rest. You will then have bug free programs.
The first rule of code reuse is - the code must be worth reusing.
If you're not sure, put it in a fucking SCM & delete away.
If only that were true. I once worked in a team where someone had written a function which took an integer and returned the same value (they were blindly following a pattern where a converter was called stringToInt, intToString and wrote an intToInt because "other cases called a function"). Two other developers had subsequently used this function (copy/paste programming)!
Delete it. Plain and simple.
Put a comment/bug id in the commit log.
What's the problem?
Pay it forward with good practice, don't comment out code. Comments are for comments, not code.
The rules were simple for this, but they got deleted.
Rewriting code?
version control + start from a working situation and end with a working situation. Where working situation means bugfree and no broken parts other than those that are going to be rewritten.
Deleting code?
version control.
Hivemind harvest in progress..
Don't ask don't tell?
I hadn't the slightest objection to his spending his time planning massacres for the bourgeoisie... (P.G. Wodehouse)
Commenting just code is fine for temporary testing/debugging/rewriting.
Leaving code in a commented state is a comment ("this is how something used to be done here"), but not a terribly helpful one. If you find yourself doing this, as well as commenting the code add a true comment stating why and what code replaces its function (the bit above, the bit below, something elsewhere, nothing (it is truly deprecated)?) and why.
Once some time has passed, unless the change is significant and there is a chance someone will come along and "unchange" it not knowing the history, such comments along with the commented code should be removed as it is all in source control anyway - but keeping it in your face (and the faces of other people working on the code) in the short term can sometimes be quite helpful especially in the case of code several people are actively looking at as one of them may quickly spot a flaw (which may otherwise go unnoticed for a while longer) that makes your new more clean/fast/bugless code far less perfect than you first thought.
If we told you, they'd no longer be unwritten.
There is only one rule -- don't replace better code with worse code.
Contrary to the popular belief, there indeed is no God.
Follow your software design criteria and your design documents, then it should be clear. One should not simply sit down and hack away changes without careful planing.
Delete, early, delete often
Can't see Hindi?
"Functionality is an asset, code is a liability." -- Damien Katz
If the code is not used you should not have the burden to maintain it. Delete it if you can. Even commented code needs to be maintained.
In the largest company I've worked for, the written rule was to explain and comment (using a specific syntax), never delete. The unwritten/save-our-sanity rule was to delete if the comments began affecting the readability of the code.
When working on code with hundreds of other developers, code that's commented out and explained/linked to a case id, can save a _lot_ of time. Say a piece of code solved an issue, but in turn created a performance issue. This did not become apparent until the code went live. The developer tasked with figuring it out isolates the affected flow and "... oh... someone added that credit check here a few weeks ago, I'll check that out first." That saves a lot of time compared to identifying dozens of involved files, then only diffing the specific methods involved in the particular flow.
They're just deleted
If you feel that you need to leave deleted code in comments for a while or forever, then your version control system isn't working. Simple as that.
Excuse me, but please get off my Pennisetum Clandestinum, eh!
don't mess with production code.
One company I worked for a few years ago happened to be using Java. They had a summer intern who wrote a bunch of time scheduling code – a couple thousand lines IIRC – to manage doing things at the correct time across different time zones. Then said intern went back to school. Three months later, when daylight savings ended, everything was off by an hour. I looked at it and found it didn't deal with leap years correctly either.
I deleted – yes, just deleted – two thousand lines of code and replaced it with about five lines to call a routine in the Java runtime library. As I recall the intern spent the whole summer working on this one piece of functionality that should have only taken about five minutes to write. They could have done a lot of other more interesting things instead.
Stupid.
If the deleted code is only a few lines, and the code represents an obvious solution, then I will comment out the code, along with a comment why the code is not suitable, e.g. "this doesn't work because blahblah".
Otherwise I just delete it, source control etc. If the newer code has a problem we can revert it.
The standards depends on the editor / IDE. There are a wide variety of choices from the classic C-h (^H), all the way to mouse editing.
Never delete, ever. Comment out. All the version control in the world won't help you if it turns out that you ignored this 20 versions ago and now don't quite recall whether it was 20, 21 or 22 ago...
Keep deleting code from a program until it doesn't work. Then put the last bit back.
It is now as small as it can be, and it works. Voila!
I am anarch of all I survey.
Unwritten Rule #1;
.
.
Unwritten Rule #2:
.
.
The other rules offered here are good, but with all due respect, they've been written.
Gently reply
Right click, find usages. Then do safe delete.
1. Don't be a theorist -- profile your code! Only consider code for deletion that's not actually used in production ... But make sure your tests pass
2. If the code you want to delete code can't be profiled (e.g. its within a method), be creative... refactor it out into a method and profile.... Or write a log entries to disk.
3. Now delete the code - be bold!
4.
5. Get your change reviewed
6. Get your build UAT tested by 'the business'... perhaps by bundling with other minor changes
7. Along with a deployment plan, have a rollback plan (and a rollback build).
You notice I didn't say "use version control". Version control is good for managing the development process. Its not a shortcut to manage the entire software change process.
I don't alter production code, ever.
If I alter code it is going to go through a test release and be tested by other people first.
I've been programming for 14 years and I've learned no matter how trivial a change I make it is very possible to do damage unless the changes are completely tested.
So, I never alter production code, only code that is due to go through a testing cycle.
I've got the best system - Every release, I zip my source and move it to a folder with every version, 0.1 to 2.7.63
1. If it works, don't touch it.
2. If it does not work, find out who did it and slap him (optional) and make him make it work.
3. If you cannot find the one who did it (or if he has been rightfully fired already), scrap and redo.
4. If code needs modification, do not modify the code but work around it.
5. Never EVER delete code. 9 out of 10 times you'll have to change it back anyway.
We used to have a Bill of Rights. Now, with the rights gone, all we have left is the bill.
My personal strategy is to first comment it out and put up a nice big comment saying why I removed it and when... then, at a later date, I'll actually remove it.(and comment appropriately about it in check-in)
The Digital Sorceress
I can't say I'm shocked to see all these comments advocating commenting deleted code. I wish you would make it easier on the hiring managers and put in your resume that is your preference so we can weed you out of the hiring process.
Years (now decades) ago I worked with a programmer who routinely replaced working/tested code with his own "streamlined" code that solved the specific problem in front of him. In other words, he deleted code that worked in the real world and replaced it with his code that solved for the test case. When asked what he was thinking, he said, "I didn't understand that code, so I replaced it with my own."
The short term result was chaos within the organization because the QA department "wasn't finding bugs" that were showing up in the field. The intermediate result was that he lost his job. The long term result was a whole bunch of hours taking out his changes and reverting code to its behavior before he was involved (not always easy after a few years).
If you don't understand code, don't delete it.
An impressive number of interrelated questions for an Ask Slashdot! Let's start by dispensing with the red herring that a bewildering number of commenters have seized on: commenting out code versus deleting code. If you have source control, then from a point of view of history as well as a point of view of executable / deliverable, commenting out code is exactly the same as deleting code.
Right! Now for your questions:
The answers may be somewhat language-dependent ...
1. No, there is no language dependency.
What best practices do /.'s use when they modify production code?
2. (For beginners) Don't.
3. (For experts only!) Before it goes to production, test your code or (better) have someone else test your code.
Generally-accepted best-practice documents regarding code rewrites.
4. If it is a complete crock of shift, rewrite it.
5. If it is only mostly shit with some gems mixed in, refactor it instead.
Generally-accepted best-practice documents regarding code deletion / What are the unwritten rules of deleting code?
This is a special case of code modification, with a large number of possible reasons why it might be the right thing to do:
6. If it is not linked in, delete it.
7. If it is never called, delete it.
8. If it has conditions that are never met, delete it.
9. If it has no purpose, worth or value, delete it.
10. If it has too little purpose, worth or value compared to the cost of maintenance it imposes, delete it.
11. If it is performance code and it has no associated performance test, it has too little purpose: see point 10.
12. If you change your mind, put it back.
13. If your fellow programmer objects, then state your reasoning, but give them permission to put it back.
Generally-accepted best-practice documents regarding code modification.
14. See point 3 above.
15. If your tester objects, you screwed up mildly.
16. If your user objects, you screwed up badly.
17. Don't screw up badly.
If it's posted in /., it is no longer unwritten.
Whatever you post / read here are NOT the answer of the original question.
If you are deleting functionality I highly suggesting leaving a permanent comment in saying what was deleted and when. Specs change all the time and the code may be needed in the future, a one line comment and hunt to SC will save from rewriting the functionality in the future. Without comments no one is going to search for it and it is lost forever.
When relying on version control, proper commit messages are the key to ensuring that you can easily find the right code later. We have these broken into 4 catagories:
AUTHOR_IS_ASSH__E The person who wrote the code isn't too bright
CODE_IS_SH_T We may like the person who wrote the code is actually bright, but may have had a bad day, ie was drinking a lot before committing
CODE_IS_USELESS Code is beautifully written, elegantly designed, but that was what we wrote before management decided what the project should do
CODE_TOO_SIMPLE Code is not complicated enough to ensure our presence maintaining it for the next 30 years, time to complicate it, pronto.
They WERE written but then deleted. Search the git repositories for a few hours and you will find them out there somewhere.
To ensure perfect aim, shoot first and call whatever you hit the target
Declare all involved "Exempt" and work them like galley slaves!
Delete the code - it's the version control system's responsibility to maintain change history. The IDE should provide some non-intrusive visual indication of sections of code that have changed in the prior version. This provides the necessary alert and the developer can investigate version control for the details.
I don't know how many, if any, IDEs support this feature, but it seems like a good idea to me.
sometimes if deleted bad code keeps showing up in the repository you need to be careful and keep the wooden stick an the hammer ready to kill it in a man-to-code combat on the local harddrive of some developer.
#1: Don't write the rules.
Sheesh, evil *and* a jerk. -- Jade
Oh my god, you can't delete code! It worked for us in 1998, and it's still working on our circa 1998 machines. What the hell are you thinking?!
Kidding aside, I comment and date old code, and add new code. It's not only there for restoration purposes (ya, ya, version control and stuff are there too), but if someone gets a new great idea on adding new code, they may find exactly that has already been removed with good reason.
When it's my own code that I maintain with no one else, I ditch the old commented code after about a year. Sometimes it sits there for longer, because it was actually good code that didn't suit that particular purpose.
I have one chunk of code in particular that won't get ditched for a longtime. It's a HTML filter, that takes all kinds of Microsoft specific characters and converts them into HTML friendly characters. I did it up better with a much smaller chunk of code, that can do a lot more, but occasionally I reference those old bits.
Serious? Seriousness is well above my pay grade.
As Wikipedia says, "Be bold." If you see code that needs to be deleted, delete it. Don't just leave it commented out and taking up space.
If you're removing functionality, then make sure you note this clearly in your commit summary, so that it can be found again if that functionality needs to be put back in.
Also, the article talks about rewriting code - throwing out the old and creating it again. This is generally a bad idea, even if you're starting with bad code, because all a rewrite does is exchange a known set of bugs for an unknown set of bugs.
Some people don't use a ticketing system to track their requirements, so have no other form of documentation for what the program does than what is in the code itself. This is especially problematic in houses where even the requirements documentation is just a doxygen header in a file written by a guy who left years ago.
You make a big change to production? There should be external documentation pushing that. Your code is in version control, but is your documentation under any kind of control at all?
(Word + track changes? Hello 1997.)
There should also be reports from your test system about dead code paths. But that is a whole other topic only appropriate for people who actually test their code. Being that is in general harder than writing the code itself...well, you can figure that quality disaster out yourself.
Either date- or version-based. "Delete after dd-mmm-yyyy" or "Commented out in 5.1". (Note how cleverly I avoid anticipating future version numbers. Management tends to change those things.)
To all the people saying "version control": I've seen enough botched configuration-management system changes and moronic branch management to know it ain't the be-all people think it is.
I work with people who say the same thing- "delete stuff and depend on code control system to get it back if you need it. That's what it's there for." However, this doesn't work over a long period of time (many months to years). Sometimes trees get moved, and history gets lost. Or code control systems change, or filenames change or get deleted, which means you have to use special commands to resurrect the file from code control. I have seen the same problems crop up on different code control software.
Due to the above, I like keeping deprecated code in a directory called "retired_code". I do this to have a reference to look back on, in case something was tricky to code, and because sometimes when I supposedly don't have to support something anymore management changes their minds, and I have to resurrect it. The size of the retired_code areas is nothing compared to the size of our trees, so disk space is not a concern. Also, I set my IDE to ignore any directories called "retired_code", so I don't get false hits when searching for things.
When removing code, consider commenting why it was removed. I've seen cases where code was removed then added back in causing bugs to reappear.
Before:
Log(“Shutting down”)
CloseLog();
Reboot();
After:
Log("Shutting down”)
Reboot();
Better:
// Don’t close the log file here because some other thread might still
// write to it during shutdown/reboot, which could cause an error dialog
// that prevents shutdown. The file will be closed anyway by the OS.
Log(“Shutting down”)
Reboot();
I don't quite get how this qualifies as news. This story points toward arstechnica which basically just summarizes(wrongly) the question and answers from programmers.stackexchange... The actual question name was "Unwritten rules of rewriting another team member's code" and covered rewrites, not just plain deletion.
Personally, my #1 rule for code deletion is:
Comment code out frist, if the product gets released with the code block still commented out, then delete it.
I'm seeing a lot of people claiming source control and deleting is the way to go and others saying commenting out code for a few versions is better. Either is fine, but the important this is that the change is properly documented. Almost no one does this. If you comment out or erase a piece of code you could leave behind a comment explaining what was done and why. It drives me up the wall when I come across a line that has been commented out which no explanation given (either in the source or in the commit notes).
Personally, I prefer the comment out for a few versions and then delete method. The reason being it is much easier to just glance at the code and (hopefully) its comment to see what was going on all in one place. I don't want to have to go looking for old code (and the reason it is not there anymore) in the source control. Better to have all the information, new and old, in one place. Just because source control allows you to backtrack doesn't make it the most appealing method.
So, when you realize a year and several thousand commits later that the rewrite neglected to handle a rare and complicated corner case, what's the easy way to find the previous version in the commit tree?
That's a serious question by the way. I'm still fairly new to VCSs, but the one big lack I see (and it may just be to EasyMercurial's stripped-down gentle-intro interface) is there's no simple way to say "show me the history of this specific section of code". Now sure, in an ideal world the commit comments would let you immediately recognize the relevant commit when you saw it, but thats still be a lot of manual searching to do. If I remember correctly hg does have the ability to trace the history of a particular file, but there are plenty of situations where a file may have seen lots of changes for lots of different reasons. Is there any mechanism available to quickly pick out just the changes to, say, a particular function? Or really, even just list the relevant commits.
--- Most topics have many sides worth arguing, allow me to take one opposite you.
How is this not an "Ask Slashdot" article?
'The tyrant will always find pretext for his tyranny.' - Aesop's Fables
That's all I ask in regards to comments -- no /* . . . */ to comment out multiple lines of code. Nothing I hate worse than spotting something in code that piques my interest only to discover there's an open /* several lines above it (often times scrolled out of my window). So I make a point of ensuring that every comment is identified on each line (a complete /* . . . */ set, //, or whatever the particular language dictates). Only exception being multi-line text or narrative -- I have no problem with that being wrapped in /* . . . */.
Yeah, yeah, I should use a better IDE that would identify all those lines as comments, but many times I'll be browsing code with nothing more than vi or grep.
1. Write the first version of the function to be simple, obvious, and portable, with no real consideration for speed.
2. If necessary, write the second version of the function to use a more efficient algorithm, but leave the first version in comments as documentation for what the new version does. If you think you have a bug, you can test it against the first version.
3. If necessary, write the third version of the function to use platform specific optimizations, in assembler, or whatever you want. Leave the second version in comments as documentation for what the new version does.
Delete code when the functionality isn't needed. Never delete code because you've implemented the same functionality in a more clever way.
When you change the structure of the code to make a more general function to handle multiple cases, write the first version in the simple, obvious way. If you decide the structural change isn't working, go back to an earlier version.
You do NOT talk about code deletion!
If you have version control, and yet still fear deleting code, then methinks your regression suite and code review process are weak.
Do you have a good handle on the coverage provided by your test suite? Is the code change, including the deletion, talked about during code review before your dev branch is merged into mainline? Does your defect tracking system allow you to tag defects with an 'incorrect deletion' marker? Are you adding a targeted test to the regression suite for every diagnosed defect?
If 'yes' to all, then delete it and let version control keep the history for you.
1. It's easier to write the second time.
Delete it all and let source control sort it out!
WTF do you mean unwritten. The code conventions for your shop should cover it.
If your changing code because the old code had a bug then you need to add test cases to your test scripts. Add tests that reproduce the bug and fail in the old code. Add good comments to the test documenting what defect the test reproduce. Then if someone goes back and reverts the change in the source the test will fail.
You don't talk about deleting code!
not that they are unwritten. There were detailed instructions on this topic.
The problem is that the instructions were deleted before being implemented.
A koan for a new age.
Depending on what is being deleted, I flip-flop back and forth between commenting out chunks for a revision or two and then deleting, and just deleting. For small sections, I tend to just straight delete. In rare circumstances I'll delete but replace the code with a comment like "Used to do X here, but now it's covered by Y" but only until Y becomes the standard and then those tend to drop off.
For larger sections or whole functions I tend to comment out first until I'm sure the new code is working then deleting it. There are a few reasons behind this:
1) There is an advantage to having the old code instantly available (no diffs, no downloading to a separate directory, etc) to make sure that all the functionality that was previous there is still in the new code. It's very nice to go back and look when the new code isn't working right to flow through the old code and see what's missing. "Oh, we used to set this flag, but when I optimized I did away with it. Apparently, someone is using it much later in the code. Guess I need to put it back." *
2) There is a standard of, when creating new database functions (a new table), that there be a set of default functions; Create the table, Load Defaults (if applicable), Insert a record, Update a record, Load a record, and Delete a record. But as time goes by developers may create more specialized versions of these functions (JOINing other key tables, for example). More updates and soon no one is using the regular functions as the specialized ones work for what they need and then some. So if I see a function not being used any more I comment it out saying, "Deprecated; try using FunctionName() instead." If nothing breaks immediately, and no one complains for a few revisions, the extra functions go away.
* The better, but not real-world, solution would be contact whoever maintains the code that used the flag and see if we can they can update/optimize the code to work without the flag.
If you have a good source code management system, you should get this ability for free.
If you don't and it's not a throwaway project, get one.
If it is a throwaway project, then there probably aren't any rules.
Once you know you can un-undelete it, the same rules apply as to adding or changing code:
* Make sure your edit improves the code.
* Don't introduce any bugs.
* If you can't avoid the previous rule, don't introduce any important or subtle bugs. Especially don't introduce any important, subtle bugs.
Knowledge is how to play a game, intelligence is how to win, wisdom is knowing what game to play.
I am not sure I can write them down, what with Russels paradox.
So now you have to go back "some time" in the future to clean up the mess you left the first time? Who's going to pay for the cleanup?
Commits should be small and should only encompass a single bug or feature, which is logged in you bug tracking system. The commit should also be tagged with the bug id.
Try and submit a patch with a bunch of commented out code to a major open source project and see if it gets accepted.
... and don't comment it out. Wrap the code in if(false) { ... }!
Srsly guise, if you're asking this question, you're in the wrong field.
The point why removing code is so hard is not, that its hard to restore. We have VCS for this.
But its hard to discover, the code ever existed. Who goes to the VCS and searches for old commits, when implementing a new function? If you weren't there when the code were in use, its unlikely you find it in the VCS instead of rewriting it.
So removing code is a decision about making it hard to find, that it ever existed.
One solution would be to remove and leave a comment behind "here was code, which was removed in a commit at $DATE". What other solutions are there, for this dilemma?
So now you have to go back "some time" in the future to clean up the mess you left the first time? Who's going to pay for the cleanup?
By "some time" I'm meaning days or weeks, not many months or more.
Slap everything commented that doesn't need to persist with a "CLEANUP" tag and scan for them pre-release or at then end of a run of sprints (and/or as you approach a release, where-ever it fits in your flow) as part of your other housekeeping tasks. Give the job to a junior so he/she might learn from the changes (have a more experienced dev to hand in case of questions, and to try make sure the wrong things are not learnt from less "clean" work).
Try and submit a patch with a bunch of commented out code to a major open source project and see if it gets accepted.
Each open source project will their own preferences and rules which are fine by me, but equally are not my problem currently (if I were to have something to contribute I'd would of course try to fit into the project's preferred coding standards (or just release my changes as-is and if anyone else wants to clean them up and claim the credit they can go right ahead, if not then fair enough too)).
Watch this post disappear and don't forget var/logs on your way out of the door.
Having JUST gone through this the only rule about deleting code is to NOT delete code someone is actively working on just because you don't understand or like it. I had about 3 weeks of work blown away by a "senior" developer who didn't understand or like what I was doing, deemed it unnecessary, and nuked it in a single check-in even though I am actively working on it without even consulting me.
Rule #1: Ask yourself, "Am I being an asshole if I remove this code?" If the answer is yes then don't do it.
I haven't thought of anything clever to put here, but then again most of you haven't either.