Become a fan of Slashdot on Facebook

 



Forgot your password?
typodupeerror
Check out the new SourceForge HTML5 internet speed test! No Flash necessary and runs on all devices. ×

How Do You Store Your Previously-Written Code? 459

Asmor asks: "I'm a novice programmer who is largely self-taught. It's never been too much trouble for me to reinvent the wheel constantly before, but now as my ambitions get loftier I'm finding that I could really benefit from maintaining some oft-used code that can easily be reused. The problem is, I really don't have any experience with this and I'm not really sure how I should organize things, how the code should be stored, how it should be implemented, etc. I think this is what people mean when they talk about libraries and/or APIs, but not really sure. I'm specifically curious about PHP and JavaScript, but advice for other programming languages is also helpful! How do you store and maintain your most frequently used code?"
This discussion has been archived. No new comments can be posted.

How Do You Store Your Previously-Written Code?

Comments Filter:
  • CVS (Score:5, Informative)

    by Anonymous Crowhead ( 577505 ) on Thursday February 16, 2006 @08:36PM (#14738757)
    Use CVS or some other revisioning system.
    • Re:CVS (Score:5, Informative)

      by g-to-the-o-to-the-g ( 705721 ) on Thursday February 16, 2006 @08:38PM (#14738779) Homepage Journal
      Mod parent up. CVS or SVN is the way to go all-round. Make sure its backed up, and set up viewvc [viewvc.org] and you'll have yourself a great place for keeping code. Not only is it easy to view from any machine, but you can quickly see a history of revisions.
      • Re:CVS (Score:5, Informative)

        by jazir1979 ( 637570 ) on Thursday February 16, 2006 @09:01PM (#14738936)
        Choose SVN over CVS, there are many good reasons for it. Also, you'll get the view cvs part for free, since you can automatically browse the repository over http.
        • Agreed. If you are starting out new, rather than maintaining old repositories, go subversion. I switched recently for a new project, and it's just plain better.
        • by slashbart ( 316113 ) on Friday February 17, 2006 @07:06AM (#14741118) Homepage
          Hi all

          Considering all the praise we read about Subversion, and its compelling features list, we switched a medium size project (80000 loc) from CVS to SVN. All in all we are not impressed with Subversion, and are not going to use it for new projects (for the forseeable future).

          The bad things:

          svn import: oops, there is a some experiment data in the directory, or an AAP subdirectory. Shit, the repository has grown by another 100 MB. No way to get it out again, unless you convert the whole BDB database to text, find your accidental additions, cut it out, rebuild the database, do svnadmin recover, fix all the permissions.

          Really wrong error messages.

          svn add *
          svn rm *.log (oops added some test runs)
          svn commit
          " unable to get lock on file blabla". You'll now have to manually do svn rm ... on every file you accidentally added. The only way to know which ones, is by committing and waiting for the error.

          Big errors:

          Having moved our repository to another server, we have had situations where a subdirectory was pointing to the new server, and its parent to the old server. When we did an svn update in the subdirectory, the updates would not happen and no error whatsover was given. Worse, to prevent this kind of problems, we had renamed the repos directory on the server, so that there was no way some dangling old links could accidentally access it.

          Adding files to a repository from multiple places around the lab has gotten us often into troubles

          The Berkeley DB format keeps changing. You can't just copy one to a server with a slightly different svn version. Worse: it will not tell you that there is a version difference, it will just try, and come up with the most irrelevant error messages.

          All in all, we find SVN not ready for prime time. Its promises are great, but at least CVS is just working reliably.

          This code is going into the Space Station (Declic [linuxjournal.com]), version control is a must for us.

          • svn import: oops, there is a some experiment data in the directory, or an AAP subdirectory. Shit, the repository has grown by another 100 MB. No way to get it out again, unless you convert the whole BDB database to text, find your accidental additions, cut it out, rebuild the database, do svnadmin recover, fix all the permissions.

            If you use fsfs, you can just delete the last revision. 1 revision=1 file in that one. Otherwise, I'd say that you've hit upon the point of having a revision control system. From a technical standpoint, not having 1 to 1 mapping of files in the repository to files in the system allows you to make cheap copies, do directory versioning, do branching easier, and make backups easier.

            Really wrong error messages.

                    svn add *
                    svn rm *.log (oops added some test runs)
                    svn commit

            " unable to get lock on file blabla". You'll now have to manually do svn rm ... on every file you accidentally added. The only way to know which ones, is by committing and waiting for the error.


            FUD. You was probably some other error in there too. I've done exactly this and it worked. Or it could be that whole "not using Berkley DB" thing.

            Having moved our repository to another server, we have had situations where a subdirectory was pointing to the new server, and its parent to the old server. When we did an svn update in the subdirectory, the updates would not happen and no error whatsover was given. Worse, to prevent this kind of problems, we had renamed the repos directory on the server, so that there was no way some dangling old links could accidentally access it.

            In the subdirectory: svn switch --relocate [new server]

            The subdirectory will update to the new place; rest of it will update to the old place. Don't blame subversion that you can't be bothered to learn how to use basic commands in it.


            The Berkeley DB format keeps changing. You can't just copy one to a server with a slightly different svn version. Worse: it will not tell you that there is a version difference, it will just try, and come up with the most irrelevant error messages.


            I guess its just me. The solution seems obvious: don't use Berkeley DB as the backend. I don't. I wouldn't even touch a database format that only works right on ext2 partitions. That's already far too picky for me. What if my ext2 partition dies and I don't have another handy?

            And the fact that you can do incremental backups and actually get only new data is a nice plus.
      • Re:CVS (Score:3, Informative)

        by Anonymous Coward
        I'd go with OpenGrok [opensolaris.org] if you have the resources. It's very fast and very powerful.
        • Re:CVS (Score:2, Interesting)

          by dgatwood ( 11270 )
          Wow, an AC with something useful to say for once. When they get it working with subversion, it might be worth a look. (For people who don't use svn, it probably is already, but I live on svn.)


    • I think if it would help if he read some background on these types of tools;

      http://www.mactech.com/articles/mactech/Vol.14/14. 06/VersionControlAndTheDeveloper/ [mactech.com]

    • Don't Use CVS (Score:5, Informative)

      by kbahey ( 102895 ) on Thursday February 16, 2006 @10:34PM (#14739433) Homepage
      Since this is 2006, there is no point in starting with CVS.

      Use SVN if you will be the only person committing stuff in to the repository. If you plan to share the code in an Open Source project with many people, and each will have their own distributed repository, then look into something like bzr from Canonical.
      • Re:Don't Use CVS (Score:4, Informative)

        by JPyObjC Dude ( 772176 ) on Thursday February 16, 2006 @11:31PM (#14739679)
        Very true.

        I analysed and deployed a SVN repository for my team two years ago and I love it more every day.

        It is stupidly easy to configure and maintain (as opposed to CVS) and very powerful. The only thing I really miss with Subversion is an obliterate command which hopefully will come around some time.

        If you have to windoze your way around, get TortoiseSVN - Once of the best Open Source Win32 projects available.

        As a side suggestion about managing your documents, it is a good idea to get anal about foldering your files and maintaining consistent naming conventions in your repositories.

        eg.
        repo/trunk/
        ~repo~/branch/dev ~~ Developmental Branches
        ~repo~/branch/rel ~~ Release Branches (Trunk branches)
        ~repo~/trunk ~~ Trunk Releases

        JsD
    • CVS is one way to go, and seriously consider it if you're going to be working on group projects.

      However, for just storing snippets (like connecting to mySQL) you can use a software program that's designed for one person like. I personally used iCodeLibrary for quite a while in college and found it helped quite a bit. If I recall it allows you to add new languages as well, since it was mainly designed for Visual Studio .NET adding languages like PHP would be needed.

      It was easy to use, but now projects
    • Re:CVS (Score:5, Insightful)

      by abertoll ( 460221 ) on Friday February 17, 2006 @01:41AM (#14740262) Homepage Journal
      Version control is good advice, but I think he/she means "how do I maintain a code library" not just how to physically store it or revisions. In other words, how do you maintain pieces of code in a way that allows you to easily incorporate them into new projects.

      For me the answer is to create individual projects or modules (using version control) that contain a logically connected set of components. Version control is really just a means to the end of actually making the library available in a convenient way.
      • Re:CVS (Score:5, Informative)

        by Meostro ( 788797 ) on Friday February 17, 2006 @07:36AM (#14741194) Homepage Journal
        This is also how I saw the question, not "what do you use for concurrent versioning?" but rather "how do i make libraries?".

        If you want to make reusable code, one thing you're going to have to do is generalize. Don't make ultra-specific functions that just do one ultra-specific thing, put in a couple of parameters to make your function more generic. That's not to say you should have one function that does everything; just don't have a CreateRadio and a CreateCheckedRadio function in your js library, have a CreateRadio that accepts a parameter for checked or unchecked.

        You may want to prefix your functions in some way so that you won't run into namespace conflicts - use your initials or something simple. The CreateRadio above would be xyz_CreateRadio.

        Group your functions logically into modules. If you have a bunch of stuff that deals with HTML form controls, make an htmlformcontrols.js library. As before, don't go overboard either way, too many functions in a library or too many libraries with just a few functions will drive you nuts.

        Use a style [wikipedia.org], and stick to it as much as possible. The most popular style I've seen is one true brace [wikipedia.org], but personally it drives me nuts to work with this kind of code. I like BSD/Allman [wikipedia.org] much better, but any style is a matter of personal preference. Use what works for you.

        Use clear, descriptive function names. Don't make function x(a,b,c) unless you have a good reason. If "nobody will ever see it and i'll never use it again," think again. Someone will see it, and you will have to use it again, and it will be a pain in your ass.

        Finally, and perhaps most importantly, comment everything. Not every line of code, but every function: what it does, what its parameters are, what its outputs are. You won't remember what $stamp is in your hash-cash implementation unless you have some kind of comment or reference you can check where you clearly stated what it is and why it's part of your function.
  • Usualy something like ":wq" "^s" "^x^s" "alt-F,a"
  • Reusable (Score:5, Informative)

    by MyLongNickName ( 822545 ) on Thursday February 16, 2006 @08:38PM (#14738771) Journal
    It's never been too much trouble for me to reinvent the wheel constantly before, but now as my ambitions get loftier I'm finding that I could really benefit from maintaining some oft-used code that can easily be reused.

    Inventing something once is Genius. Inventing something twice is stupidity.

    Using OOP, code should be reusable without having to have some external database. I find that the more external processes one has, the less likely one is to use it.

    Code should be self-documenting. I'm not saying you don't have external documnenation... just that well written code has good comments. A good practice is to comment function and classes before coding.

    Break things down into components. Refactor. Then your code will be very reusable.
    • This is similar to how I do it. Most of my programming anymore is done in .NET, so I've created a set of libraries, organized by the scope of the work (Database/IO, alrogithms, network transport). I then used nDoc to create MSDN-style documentation that I can easily search later on if I need to code something similar.

      That way I can locate the exact class, make sure that it suits my needs, and copy it over (along with any dependencies) into the project quickly and easily.
    • Re:Reusable (Score:2, Insightful)

      by infochuck ( 468115 )
      What? What does any of this have to do with the question? He didn't ask for the features of OOP; he asked how to store/organize his libraries/modules/classes/headers files/what-have-you. The implication that simply using an OO language - regardles of the exact language or platform - obviates the need for basic file storage and management is ludicrous.

      On top of all that, source repositories (I assume that's what you mean by "external databases") aren't primarily intended to help folks oranginze and store
    • Re:Reusable (Score:3, Insightful)

      by Nutria ( 679911 )
      Using OOP

      All I can say is, "Wow". Code reuse has been around for 40 years.

      FORTRAN card-wallopers would keep routines as stacks of cards in their desk drawers. The C rtl is reusable code, as are libm, Turbo Pascal units (am I dating myself?), SQL stored procedures, GTK, the 10 jillion Perl modules, etc, etc.

      I don't know much (anything, really) about how PHP and JavaScript store software, but if this were a 3GL, you could group your common code into funtional units that compile into .o/.so (or .obj or .dll,
    • Re:Reusable (Score:4, Insightful)

      by Eivind Eklund ( 5161 ) on Friday February 17, 2006 @05:08AM (#14740868) Journal
      Note: The following may not apply to some totally exceptional programmers. However, unless you've got at least ten years of professional experience, assume it applies to you and you just don't have enough experience. I've never met nor heard of anybody it does NOT apply to.

      This seems reasonable when one don't actually write real world code, instead just playing around with "what I want to do". Often, reinventing the wheel is cheaper than trying to use an old wheel, and trying to make something that can be perfectly reused is more expensive than writing it several times.

      Writing things several times also leads to you knowing what things you did right and wrong, so the second or third time you do something similar can be much better. It's important to be careful on go #2, though - it's easy to try to solve all the things that were bad with the first system, and overengineering. That's known as "The Second Systems Effect".

      Eivind.

  • by Profane MuthaFucka ( 574406 ) <busheatskok@gmail.com> on Thursday February 16, 2006 @08:38PM (#14738772) Homepage Journal
    Store you code on a disk or a tape. If you store it on a printout, you'll just have to type it in again.
    • duh, you use a hi-speed scanner and OCR, that's just as good, right? Right?

      As a related idea, I've often wondered if it would be possible to port Doom to a high-speed printer, where it prints each frame on a separate piece of paper. Not eco-friendly, but that's not the point.
      • I've often wondered if it would be possible to port Doom to a high-speed printer

        Already been done, mostly. There exists a vt100 doom port, which could be easily converted to a line printer and timed to a strobe.

    • It's the duty of noob developers to work their fingers till they bleed. So, printing it out is the best choice.
  • SVN (Score:5, Informative)

    by anielsud ( 739476 ) on Thursday February 16, 2006 @08:40PM (#14738795) Homepage
    I run a small web dev firm that does a lot in the way of PHP and JS, like yourself. What we have found works the best for our core library is a copy of Subversion [tigris.org] running on our server. This way we all know exactly what the latest version is, and more importantly we can see how it became the latest version (i.e. what changes were made). A lot of tools run with SVN nicely. For instance, Trac [edgewall.com] talks to a backend copy of SVN and couples it loosely with a wiki and a couple of other things. A lot of hosting providers will also run a copy of SVN for you, like http://networkredux.com/ [networkredux.com] (We just switched over to them).

    Of course, a root level folder on the ftp server can also work.
  • Old code (Score:5, Interesting)

    by SysKoll ( 48967 ) on Thursday February 16, 2006 @08:41PM (#14738805)
    I have code I wrote 15 years ago in an "archive" dir in my home directory, subdivided by projects.

    Whenever I change my main machine, that dir is of course copied to the new one, and included in the backups. Organiwing the libraries by functionality and language would be a nice thing, but I never seem to find the time.

    Beware, though: Most employers specify that code written by employees belongs to the company. If you write code as a corporate employee and then leave your employer, you should really think twice before carrying that code with you. If your new boss thinks you are copying code written in a previous job, he would have to throw the book at you.

  • by jkauzlar ( 596349 ) on Thursday February 16, 2006 @08:45PM (#14738837) Homepage
    In an ideal world, I would have my libraries kept in some safe server-space somewhere, probably with versioning control implemented. Then I would organize the code into directories for each language, and then by usage, then the actual package. You're probably not going to access it THAT much, so a descriptive readme file with each package would be necessary as well. Nor would you probably need an advanced cataloguing system... but a fun project would be to create a web-based one.

    In the real world, though, I just copy code from previous projects into the new one as needed. I'm usually careful about keeping things modularized so this hasn't been a problem so far, but I tend to forget what I was doing on my old projects and have to spend time figuring that out.

    I'm not sure if there's software for this or not. Did you try searching for 'code' on freshmeat? :)

  • I have an external HDD for my laptop. It holds a nightly backup of my SVN repository. I also zip up my source trees every so often and upload them to my webserver. I've been burned too many times by losing old code -- so now I hold onto it obsessively.

    I also press them to DVD along with other files whenever I am trying to make a "get more free space please" backup.
  • Gmail. (Score:5, Interesting)

    by JohnnyLocust ( 855742 ) on Thursday February 16, 2006 @09:02PM (#14738944) Homepage
    I just use 7zip to archive my nighly builds, and email them to myself on my gmail account. I put the comments on the code in the message body. Gmail gives you over 2.5 gigs of storage space, and you can search you message bodies and headers. I can also retrieve my code and projects from anywhere in the world, and don't have to worry about hard drive crashes.
    • That's smart. I've got a CVS repository on my main machine that's rsync'd nightly to my laptop and a remote box, but I like your idea better :).
  • Put it on the web (Score:4, Interesting)

    by republican gourd ( 879711 ) on Thursday February 16, 2006 @09:08PM (#14738969)

    If it isn't likely to turn around and be immediately salable, turn around and put it on the web. I've found that doing the extra (minimal) effort of bundling up and organizing the pieces that is necessary for web presentation really does wonders over my previous storage scheme (put it on a cd, then lose the cd).

    I've got about a year's worth of random stuff thus rescued now, even as I kick myself over the things I know I wrote but can't find anymore. For what its worth: Here it is [elifulkerson.com]

  • by mhanoh ( 303815 ) * on Thursday February 16, 2006 @09:13PM (#14739003)
    Get a subversion over http (apache) server going and turn on web-dav auto-commit.

    This way you can have full version control with a client like Tortoise SVN and read access to any file with any web browser.

    The web-Dav auto versioning will allow you to write to any of your files with any web-dav client including windows explorer, internet explorer, ms visual studio, macromedia home site, cold fusion studio, many other development environments, microsoft office and lots more.

    Subversion info: http://en.wikipedia.org/wiki/Subversion_(software) [wikipedia.org]

    WebDAV info: http://en.wikipedia.org/wiki/WebDAV [wikipedia.org]

    Subversion: http://subversion.tigris.org/ [tigris.org]

    Tortoise SVN: http://tortoisesvn.tigris.org/ [tigris.org]
  • my system (Score:5, Funny)

    by Kohath ( 38547 ) on Thursday February 16, 2006 @09:19PM (#14739038)
    I usually print it out and staple it to a squirrel. Then I set the squirrel free, because information wants to be free, and so do squirrels with paper stapled to them.
  • by zobier ( 585066 ) <<ten.reiboz> <ta> <reiboz>> on Thursday February 16, 2006 @09:22PM (#14739058)
    I often find that adding comments in the PHP/MySQL/Whatever manual under the function you are using is helpful. That way next time you are looking up how to do something (maybe a year later) your snippet is waiting for you. Also writing articles about how to do something and getting it posted on community code sites is good. Otherwise I'm a fan of plain text files or just keeping copies of the projects you work on and poking through them later. I find that I incrementally improve on my foundation code over time. I don't believe that re-writing code is a bad thing.
  • Modularization and reuse are sort of like, fundamental concepts to good programming. First you need to at LEAST be familiar with the constructs provided by the languages you are using. That will probably lead directly to your strategy. As far as "storing" the libraries that should be no different than storing any of your other code, reused or not. Subversion is a good choice. Although to be technically correct, one must make a distinction between version control and storage/backup. Don't use one for th
  • API's and Libraries (Score:5, Informative)

    by sterno ( 16320 ) on Thursday February 16, 2006 @09:37PM (#14739147) Homepage
    I think this is what people mean when they talk about libraries and/or APIs, but not really sure.

    Not quite. What you are talking about sounds like just a repository of random code. A library is a specifically designed set of code to perform a given task or set of tasks. There's a certain amount of order implied in the term just as is implied by that big building where they put books.

    API's are designed interfaces to a system to make coding easier to do. You don't have to understand how the underlying guts of the code works, you just program to work with interfaces. So you call the draw() method and a line appears on the screen but you don't need to know how to speak directly to the video card, etc.

    AS for the original question, I have two suggestions. The first is to use CVS as a way to version your code. It's like have CTRL+Z for your entire project. It makes it much easier when you are adding new code because you can feel comfortable breaking it completely because you know you can revert it easily.

    The second is to use a simple search engine to catalog your code. Google desktop would be up to the task. Just check out your code from CVS and put it in a directory somewhere. Then when you need code for some task you can search for it. If you're good about commenting your code, that should work like a charm.
  • I store my previously written code in my previously written programs. If I need a snippet of code I just open my previous projects code and grab it.
  • Well, that's easy. I have two folders: "Projects" and "Archive". "Projects" is divided in folders, my current projects. "Archive" is previously written Projects. Archive has folders for language etc. All in all my programming folder is 2 GB. Code others have written I save in a completely different place.
  • two issues here (Score:5, Interesting)

    by blue_adept ( 40915 ) on Thursday February 16, 2006 @09:52PM (#14739209)
    One issue is code re-use.
    Code re-use is why you write API's and create your own libraries, so that you don't have to keep re-inventing the wheel.

    The other issues are version control, code management, etc. Some ppl here are recommending cvs and other such overkill. If your a novice PHP coder, none of that matters; you probably have a handfull of scripts that weren't written with re-usability in mind, and therefore are minimally reusable (written in a language that doesn't encourage re-usability to boot) so theres no "tool" that will magically let you squeeze the juice of re-usability from stone.

    At this point, you biggest concern should be storage for sake of making frequent backups. Personally, I encrypt whatever folder I'm working in (using PGP) and email it to my gmail account every day. That way it's accessible no matter where I am, and pretty secure too.
  • why punch cards of course, what else would you use to store your code?
  • 1 file (Score:3, Funny)

    by MrCawfee ( 13910 ) <mrcawfee@yah o o .com> on Thursday February 16, 2006 @10:04PM (#14739275) Homepage
    You do what i do, you put everything in one file and call it "misc" and then link it to every program you make. problem solved.
  • Sourceforge (Score:3, Informative)

    by zanderredux ( 564003 ) on Thursday February 16, 2006 @10:06PM (#14739285)
    I create a project around it and submit to Sourceforge as a GPL project. Someone might get interested in the stuff and the APIs could have a chance to have a life of their own.

    Once in Sourceforge, you get CVS and all the goodies. Better than using GMail for it.

  • by Peter Cooper ( 660482 ) on Thursday February 16, 2006 @10:08PM (#14739296) Homepage Journal
    If it's not sensitive, and I wouldn't mind people using it, I like to store it on my tagged code snippets site [bigbold.com]. It helps me find useful bits and pieces again at a later date as I can always remember a word or two which I tagged it with. 1000 other users seem to enjoy it too :) and if you're looking for inspiration you can subscribe via RSS.
  • Is learning how to break up your programs into multiple files. In C, learning to do this is tricky... from there it's not far from calling an external function from some library you've linked in.

    In javascript or PHP, there is syntax for loading external files. Play with it, do dumb little experiments. Make up a file.js that just runs and alert(), and then call it from another, and see how it pops up a message box just as if you had called alert() directly.

    From there, it's only a matter of thinking up functi
  • I've been in your shoes for fifteen years now. I originally learned programming to play on the Commodore 64, but really took it up when I was a SysOp of a BBS (WWIV 4.2 at the time, tons of mods out there, some of them quite good). I started writing my own utilities and tweaking mods to suit my own liking. Believe it or not, but I still have most of the code from back then. It has shuffled through a dozen various machines and hard drive upgrades. I've learned a few semi-obvious things about keeping trac
  • Beyond archiving, the best advice I could give is

    1) Use comments -- good ones! -- liberally. Check out a programming style guide. There's nothing worse than coming back to your code a year later and asking, "What the *&$#^& was I thinking here?"

    2) Learn how to make your code general enough to be reusable. Limit your imbedded constants to a minimum. Write functions to solve the general case. Your code might run slower, but unless you are doing serious number-crunching or searching, it won't matt

    • by geminidomino ( 614729 ) * on Friday February 17, 2006 @12:01AM (#14739826) Journal
      There's nothing worse than coming back to your code a year later and asking, "What the *&$#^& was I thinking here?"


      Not true.

      You could come back to your code a year later and think: "What the...? What kind of "Teach yourself C in 24 hours" mental midget committed THIS? This idiot should be fired... into space! He's...uh... oh, damn..."
  • email (Score:3, Funny)

    by rich_r ( 655226 ) <.rich. .at. .multijoy.co.uk.> on Thursday February 16, 2006 @11:03PM (#14739517) Homepage
    To Chuck Norris. He's got infinite storage space, but recovering the files will almost certainly involve a roundhouse kick.
  • If you're talking code snippets, use a well organised directory (one directory per set of related code/project, multiple versions under subdirectories). Biggest advantages: Highly portable and very simple. No reliance on other software Biggest disadvantages: Multiple versions are hard to manage.

    I have to confess that since I'm not heavily involved in much hobby and open source work I still use a simple directory most of the time at home (and on my personal laptop). I'm sure some will laugh/scoff.

    As you prog
  • by ebuck ( 585470 ) on Friday February 17, 2006 @12:13AM (#14739874)
    Storing your code is just the beginning.

    But to start, use SVN. There's not a good reason to use something else, and having the history of your changes will (in some ways) be far more important than having the code itself. If SVN is a bear to put up with, and it's just you, you might consider RCS, but RCS will eventually make you jump through so many hoops that sooner or later you'll be looking at SVN.

    After that, you'll need to recode your code to become more useful over time. At first, the solution fits the problem, and the problem fits the website, and that fits the specific task you were trying to perform. After some time, your needs will change. The second time you want to use your code, you'll notice that it doesn't really fit. This is where your challenge starts.

    Challenge yourself to NOT write the 2nd and 3rd products that use your code to make compromises for the "way this library needs to be used". Rework parts of the library to make it more useful in more situations, and rework both the old and the new projects to use the new library.

    Then try to make a third application that uses the library in a slightly different way. Once again, don't write the application to fit the library, but modify the library to fit the way the application uses it. At the same time, check that the old applications both keep working on the rewritten libarary's code, and keep them up to date with the changes in the library.

    After a few trips on this merry-go-round, you'll begin to notice a few things about code maintenance, code reusability, and code maturity. Sure, you could just read about it in a book, but that would rob you of an education. You MUST see it happen in person to understand it. If you're doing things "correctly" you'll notice a few things:

    1. Each time you write a new applicaiton, the library needs to change less and less, but it's still easy to use.
    2. Good libraries don't force different applications to be written the same way. Bad libraries require the application to be written in ways that make using the library uncomfortable.
    3. It's impossible to make code reusable without some understanding of the various ways you might be likely to use it.

    The real test is when you find yourself writing documentation for your library so you can hand it off to someone else to use without the need for them to see your source. Sure, you could give them a copy of the source code too, but if they have to read it, you've only made it reusable for you, and that's a small audience to learn from.

    Good luck, and don't worry if you fall short. Writing good, flexible, reusable libraries is often much harder than writing the applications that use them. Just remember, it's not a library if only one application uses it. It's not flexible if only one style of application uses it. It's not good if you have to read it's source code or documentation that looks like it could be source code.

    Sincerely,
    ELB
    • There are often good reasons for using distributed VC systems (Darcs, monotone, Arch, BitKeeper, etc) instead of SVN.

      There MAY be a good reason to use CVS in that CVS is slightly more trivial to set up; this Subversion tutoral [artis.imag.fr] makes the SVN setup fairly painless, too, though.

      Subversion is likely to give you less pain in the long run than CVS, though.

      <soapbox>
      I think SVN's lack of distribution support might end up being the worst thing to happen to open source ever. Distributed development can b

  • This is only good for home/local use:
    I have a special subirectory called "code" within which I have folders for each language I've worked in for whenever I've had something I want to save. These will either be the first few tutorial-level programs I've written in that language, or complete programs where I saw some reuse in the future. I can quickly search ("grep") within the files for functions, keywords, and such, either as a memory refresher for writing a different program, or to cut and paste and modif
  • by steveoc ( 2661 ) on Friday February 17, 2006 @01:14AM (#14740157)
    This is one of the most complex problems in the realm of computer science, and the answers to this question are less than obvious.

    What you need to do is reduce your code samples to a numerical matrix, assigning weights to various functions co-dependant upon the language that is being used in each case.

    These matrices can then be overlayed in an N-dimensional space, and the resulting eigenvalues plotted .. I find that a typical Euler-lagrange transformation works a treat, especially when numerising C code.

    For C-like languages (such as PHP), then a modified transform, such as the "saddlepoint" method used by Ridderinkhof and Loder is often more appropriate.

    Once these transforms have been completed, computed, stored and plotted .. you now have a basis for a firm statistical analysis, and you are now on the road to the enjoying the luscious fruits of code-reuse.

    Now you need to apply that numerisation of the coded functions across an (N+1) dimensional space, which is in fact - the source code to which the said functions have recently been applied. Time scale here is critically important - as the most recently used invocation of a function must by the merits of its use, hold a higher weight than one which has not suffered invocation for some considerable period. This is the much-discussed 'Wolverton-Hasselby functional relevance decay factor' which is often the subject of many a debate in computer science circles.

    Having thus reduced the chaotic collection of functions to an orderly numeric topology (the graph of who's actual usage forms an ever-revolving surface spread across a time-dependant dimensional plane), we soon find by observation that the collection of functions now forms a pyramid.

    Further quantum statistical analysis of this ever growing and ever evolving collection of co-dependant functions will reveal that the structure of this grouping forms not just a pyramid (no surprises there), but a SIX SIZED pyramid !! A pyramid with the base of a perfect hexagon is formed when this numerical matrix is rendered as a 3D image.

    The ratio of the height of the pyramid to the size of the base is the value of 2/pi.

    There are writings in Babylonian that hint at the architecture of the inner structures concealed within the Ziggurat of Ur .. and that these structures are also .. you guessed it ... a six sized pyramid with a structural ratio of 2/pi. One more peice of evidence which confirms the widely held (but seldom admitted) secret knowledge that the ancient Sumerians were masters at the art of computer science.

    So .. ah .. yeah, there you go. You should reduce your code to numbers, store it in a hexa-pyramidical structure, and continue to statistically analyse the usage of these functions until such times as your hexapyramidical representation of those functions reaches an ideal ratio of 2/pi. At that time, you know that you will have reached a higher plane of computing expertise. Take pleasure in this moment and revell in it - but be aware that such knowledge only opens the doors to longer and steeper pathways, beyond which lay more secrets yet to be uncovered.

    Best wishes on your journey

  • Unit Tests (Score:3, Informative)

    by Anonymous Coward on Friday February 17, 2006 @02:23AM (#14740400)
    From my experience:
    - If you have unit tests, keep them with a copy of the program that runs them.
    - If you dont have unit tests keep a running little example of how to use it - and start looking into using test-driven development for these pieces of code you'd like to rely on.
    - have a 'code blog' in a plain txt file where you track some of your main decisions and ideas to-do. As time goes by, I have tended to idealize my past code into doing things I had only wished it did :)
    - If the code uses databases, external files, etc. keep those too
    - If there are interesting things that need to be done during build, make sure you keep those too
    - Choose some SCC mechanism, svn or whatever suits you, plenty of posts...and archive a plain copy of the
    - if you plan on archiving for maaany years and writing in some propietary lamguage, keep a version of the editors & compilers safe with your code. I had to rehash a lot of prolog once.
  • by LoveMe2Times ( 416048 ) on Friday February 17, 2006 @03:48AM (#14740636) Homepage Journal
    I've been programming for 20 years now, and I've worked in a variety of languages during that time on a lot of different things. And you know what? All of the code that I ever wrote before has pretty much zero value now, with a few exceptions. Especially at your phase of development as a coder, I think you'll find the value of code reuse after significant time has elapsed practically non-existant. Why? Well, because you'll find that your abilities grow substantially every couple years, and you're almost always better off to start with a clean slate rather than fooling around with your old code.

    Now, there's a few caveats here. Another thing that happens over time is you learn to stop re-inventing the wheel and to use pre-existing libraries. Right now, you're just unaware of their existence, but you'll learn where to look if you make a little effort. In fact, you'll find that existing libraries tends to heavily influence choice of language to use. So it turns out that most things that are really worth reusing are already available, and you should use those solutions rather than maintaining your own. Sure, write your own for fun or education, but when you get a serious project, you've got no use for it. In some cases, you'll find that there's no library available, so you write something from scratch, but 3 years later, you find that somebody else has made a nice library that's much better than what you hacked together. Several times I have ported code from my own hacked together solution to a more mature library. It's a natural progression, and there are a thousand times more libraries freely available today versus 10 years ago.

    Now, having said all that, there are still times where you want to make something that is generically reusable. The point is, though, you should really make an effort to make a library out of your code. I have done just this on a handful of occasions. Then, put it up on SourceForge or something similar dedicated to your language of choice. I have a few libraries up on SourceForge, some only a few hundred lines of code, but some other people have found them useful because I made the effort. Other people have suggested CVS or whatnot, and SourceForge will give you that.

    Maybe the real gist of your question, though, was about making your code into a library? While the technical details of making a lib, dll, so, jar, pm, etc vary from language to language (sometimes compiler to compiler), here's a few pointers:
    1. This is just good practice in general, but you have to make the code *independant*. It has to stand on it's own. You might have heard about encapsulation, this is what they're on about. Make sure your application code no longer has to make any assumptions about how the library works. Get rid of "magic numbers" and define well-named constants. Make some effort to make the libraries data protected so app code can't screw it up.
    2. Make all of your functions meaningfully named. Make sure each function sanity checks it's inputs. Return meaningful errors anytime something goes wrong. This can be the hardest part. You have to check for and return errors *rigourously*.
    3. Define error constants, and provide a function to get a meaningful error message as a string. Alternatively, if you're using exceptions, make sure the exceptions can provide a message as a string.
    4. Provide appropriate initialization and cleanup/shutdown routines. Clearly define whether or not the library or the application "owns" any resources (memory, file handles, database connections, sockets, and so forth) so people know whether or not to release them.
    5. Make an effort to decompose your functions to expose a fine-grained interface, and then write "convenience" functions that use the low level functions to implement common needs. For example, if you have something that opens a file and processes it, break that down into something that works on a memory buffer and provide a convenience function that opens a file and feeds it into the memory buf
    • by dasil003 ( 907363 )
      All in all good advice; I have some additional tips for PHP.

      I think the number one issue for code re-use is avoiding name collisions. PHP doesn't support namespaces, so my approach has evolved to building classes, even for very procedural functionality. I have one library named after my (very unique) username that contains all the functionality that I find useful for my own projects. I usually repackage any functions I use from there in the case of outside projects that other people will be working on.

      I

The price one pays for pursuing any profession, or calling, is an intimate knowledge of its ugly side. -- James Baldwin

Working...