50

I learned very early on that cutting & pasting somebody else's code takes longer in the long run that writing it yourself. In my opinion unless you really understand it, cut & paste code will probably have issues which will be a nightmare to resolve.

Don't get me wrong, I mean finding other peoples code and learning from it is essential, but we don't just paste it into our app. We rewrite the concepts into our app.

But I'm constantly hearing about people who cut & paste, and they talk about it like it's common practice. I also see comments by others which indicate it's common practice.

So, do most programmers cut & paste code?

3
  • 11
    Even if I know how to do something, I will often search for code samples anyway for best practices. Once you can read code, you can quickly tell whether what you find is better than what your plan was.
    – Nicole
    Jan 15, 2011 at 1:04
  • There was a question regarding cut & paste pretty recently. Why don't you check it out?
    – Naurgul
    Jan 15, 2011 at 10:48
  • If I understand it.
    – johnny
    Apr 17, 2014 at 16:52

13 Answers 13

48

Two general cases:

From one project to another:

Most programmers cut and paste code in this capacity. They might find a previous project or something online and copy/paste it exactly or copy/paste and make changes to it. I think this practice is typically fine. This is especially good when it is proven code. (Examples: Some sort of utility object from a past project that worked well, or possibly from a blog with few changes needed). Where this can be bad, is when you are copying code that you don't understand, or where the code is poor, or where there is a much better alternative solution than the code that you are pasting.

Inside the same project: Copy and pasting in the same project is typically not a good idea. This is a bad smell that the code that is being copied should just be in a method/class somewhere and called repeatedly. There are some exceptions to this, but generally the programmer should be thinking: "Is there a way I can parameterize this code that I am copying?".

9
  • 5
    Generally this is true, unless you're writing code which requires anti-patterns, as might be the case with antitampering code, such as for software licensing. Jan 15, 2011 at 0:15
  • +1 Yeah, I've done both these things. I haven't done cut & pasted code from within the same project for a heck of a long time (although I'll confess to rarely doing it under extreme pressure with logged bug to comeback to it). As for utility classes, my project to project copying is now isolated to copying complete files. Jan 15, 2011 at 7:11
  • 2
    When writing database code, I usually cut and paste some of it into a new function and modify the sql itself to obtain desired result and need not concern myself with re-typing some of the prerequisites to make said database calls. Although in general I agree with both remarks.
    – Chris
    Jan 15, 2011 at 16:10
  • 1
    @Chris: Copy and modify the heart of it is very different than simply pasting it as is. Jan 16, 2011 at 4:17
  • 1
    @Loren Pechtel: Nonetheless it still involves the act of copying and pasting code.
    – Chris
    Jan 16, 2011 at 15:28
37

Most programmers do it, but that doesn't mean you should

One of my programming mantras is: "If I am copying and pasting code, I am doing something wrong". Essentially, DRY.

I think it should be obvious that code reuse means using code as a resource, not repeating code. Sometimes I've copied and pasted code my own code, on most cases I end with boiler plate code or stuff that looks really similar.

After investing some more time with that code afterwards I end up with the following:

  • A component (see also: separation of concerns)
  • I can resort to reflection to make things simpler, cleaner and more easy to reapeat in the future.
  • A better design, because even if it works, why not do it all over again after you learned the lessons?.
  • A pattern that I can abstract, turn into a library component, and remove duplicated code.

It can be debatable whether we should or shouldn't copy & paste code since the client/boss doesn't care (at least directly and in the short term) and you might end with the same results, but the problem really comes when it leads to bugs, loss of modularity, and ultimately, maintenance hell.

What you should do: refactor ASAP

Nobody writes perfect code, even if it works, even when you are not copying & pasting and it is your own code, if you are not quite satisfied with it just put a note in comments (e.g. a docblock "@todo") to remind yourself what to refactor and why... even if you don't refactor it yourself, it might become the difference between happiness and total frustration for the maintainer.

Eventually, you'll end with good code in the end, even if you copy and paste.

Good Code

via XKCD

4
  • 19
    I've often seen "refactor later" turn into "refactor never", or even worse "I'm such a hot shot some other SUCKER can refactor and fix my nearly-but-not-quite-ok code". I'm a believer in doing it right up front, cos otherwise its like tomorrow - it never comes. Jan 15, 2011 at 6:13
  • 2
    @quickly_now - re: "I'm such a hot shot some other SUCKER can refactor and fix my nearly-but-not-quite-ok code" ... I can't express to you just how much I hate those jerks. Jan 15, 2011 at 7:18
  • 2
    Hey John. I hear you. I spent years of my life being that sucker... paid half as much and sweating until midnight getting a really good understanding of whats going on (and re-writing great slabs of crap code) - while the hot shot went on to screw up something else. Sigh. Jan 15, 2011 at 10:22
  • 1
    The more people in the team, the more "refactor later" becomes "refactor never" as far as I could see :/
    – wildpeaks
    Feb 7, 2011 at 15:19
8

When I'm stuck and search for stuff to solve my problem and happen upon some helpful snippet of code that does what I want, I naturally copy it. Sometimes it's just the gist of it. I then change it to suite my needs. This happens more often when I delve into things that I am not an expert in (currently, Objective-C).

I always take the time to learn something from the code, so for me it's a great way to learn and to avoid reinventing the wheel.

4
  • 4
    I've always said 'a good developer is a lazy developer'. I don't reinvent the wheel if someone else has already done it. But I keep it small...I never copy more than a few lines of code, and never anything I don't understand completely.
    – morganpdx
    Jan 15, 2011 at 1:07
  • I'm all for learning from others, but don't you find that unless you're looking for a specific problem, just wrapping your head around what the other person has done is more time consuming that just doing it from scratch? (notice I'm talking about 'code', not complete units of functionality like classes, etc...) Jan 15, 2011 at 7:21
  • @John MacIntyre Could be, but usually when I pop in some small code snippet, I mold it until I'm satisfied with it. Often it needs to be adapted (into a function, more generic, improved, optimized etc) anyway. Jan 15, 2011 at 10:41
  • @John: Snippets of code provide those pieces that show you how to do things. Of course, cut and paste. But like Martin points out - learn what that code is doing. You will spend much more time searching for a specific method you don't know the name of. When you don't know what a word means; you look it up in the dictionary. Definitions are 100% clear; but how often do you look at the usage samples? Code examples are just like dictionary usage samples. MSDN doesn't always include usage samples, or are often incomplete.
    – IAbstract
    Jan 15, 2011 at 17:36
6

I'm going to talk about copy/pasting other people's code here. Grabbing parts of my own work from my personal library is fair game. I know them and understand them by definition.

I find that the most frequent situation where I "cut & paste" code is when I have a particular problem and I run into a blog post that solves it. Most times I retype the solution into my project (after all, it's probably written in the blog author's style, if nothing else). It's not really my code, but I don't feel bad about using it in that scenario.

Going out and grabbing entire methods or systems to paste them into my project as-is and call it done is something I don't understand. There was a question on StackOverflow the other day that perfectly illustrated the problem with doing something like that.

Cobbling together a Frankenstein monster out of different code parts just can't be all that efficient. I mean, if you get good at it, that means you're either replicating the same solution over and over again or you've obtained enough understanding of other people's code that the same level of copy/pasting should no longer be necessary and your productivity would improve through not having to resolve issues between incompatible code samples.

I personally have not met many programmers who copy/paste on a large scale. I've seen plenty who code themselves into the deepest and darkest corners, but that's a different story. Based on my personal anecdata, I'd say that most programmers don't copy/paste entire applications together, but it's really hard to say for sure.

8
  • 1
    Maybe many programmers don't copy/paste actual code on a large scale, but they will happily leverage a ready-made library (free or otherwise) without looking at a single line of code...
    – hplbsh
    Jan 15, 2011 at 4:52
  • 2
    @Stuart True, but I think the distinction there is that that library wouldn't be claimed as the programmer's own work. And honestly, so long as the library works and does what I need it to do, I don't particularly care to pore over its source either. (Assuming due diligence is otherwise done on how reputable/reliable the library is in the first place.)
    – Adam Lear
    Jan 15, 2011 at 5:15
  • In a way it's a matter of intent, both on the part of the publisher and the consumer :)
    – hplbsh
    Jan 15, 2011 at 5:18
  • @stuart - I wouldn't include a library in this discussion as it's a cohesive unit ... not really 'lose' code, if you know what I mean. Jan 15, 2011 at 7:25
  • Actually thinking about your comments, I honestly have to wonder if its possible for a programmer to cut & paste a complete system together. I think the weight of their hubris would quickly avalanche, crushing their progress to a standstill. Jan 15, 2011 at 7:28
4

As a new programmer (4 months into my first job), I rely on help quite a lot (whether from SO or other places). I make a point of NOT blindly copying and pasting others code. Even if the code provided is what I will be using, I will type it into my program and then spend a little time making sure I completely understand what it does and the reasons for it.

I want to ensure that I am constantly learning and not simply an expert in cut and paste

4

Bad: Copying and pasting the same block of code over and over again

If you find yourself doing this, you should probably take a second to think about what can be abstracted out of the code being copied and create a function/method to handle it. This is where the DRY (Don't Repeat Yourself) principle counts.

Good: Copying a block of code that's known to work

DRY (Don't Repeat Yourself) also applies here, just in a different sense. IE, don't repeat work you've already done in the past. If you have taken the time to write a section of code, debug, test it, and it's proven to work in a production codebase; you'd be dumb not to re-use it.

Most people give copying-pasting a bad rap because many beginner programmers spend their time scouring the net and copying/pasting a mishmash of other people's code without understanding what it actually does.

Writing everything from scratch every time isn't any better. I know there are a lot of old school purist programmers that thing everything should be written from scratch and I hope I don't get stuck working with them. If you have 5 years of programming experience, you should have a pretty substantial library of code that's prime for re-use. It's one of the best assets an experienced programmer can bring to the table because it'll potentially save a lot of development time.

If you don't understand with your old code does at first, take a moment to read the comments and re-familiarize yourself. If your comments suck... well, that's another issue altogether.

3
  • 1
    Instead of copying and pasting code, it's entirely possible to write it in a reusable way. Then use that instead of copying and pasting it.
    – Bjorn
    Nov 8, 2016 at 19:52
  • 2
    @BjornTipling Yes, it is usually preferable to break code down into reusable functions unless that process adds complexity and the code will never be reused Nov 17, 2016 at 1:34
  • If you're copying and pasting it, you are reusing it. I agree people should use their heads and that the conditions may warrant it. I have found myself doing copying and pasting when writing tests, but even there I try to create reusable functions, but then there are like two or three lines that are nearly the same, but I can't quite generalize it enough to turn into a reusable function.
    – Bjorn
    Nov 17, 2016 at 2:08
3

After 25 years of writing code, there have been times when (with no access to code I wrote for a previous employer) I've wished I could cut and paste. HOWEVER this has been very rare (and keep reading).

Perhaps the best example is a really simple command line parser I came across years ago for unix operating systems. A simple loop zipping through the args and processing the options. It was devlishly simple and elegant, and I've used that (more as a pattern than as a literal cut and paste) many times since. This is the exception rather than the rule.

Usually a plain ole cut and paste is completely inappropriate - its more cut and paste the concept, or algorithm, that has been important.

I'm not too proud - I'll happily search around to find a really fast parity or hamming code verify algorithm or something exotic like that. Then spend a few hours understand it to see if it really is the massively super-fast thing I was after, or a naive pile of junk.

I worry every time anybody merely copies code without pausing to understand it. They are either a genius (understand it and all its subtleties in a glance), or a fool. There's not much room for anything in between. Oh, and there are not many true geniuses either.

Without understanding, you really have no idea what you've just thrown in REALLY does, under not just the happy but also the unhappy circumstances or input conditions. Sometimes this does not matter cos you get lucky. And sometimes this makes for much long term pain.

1
  • 5
    on the other hand, there are programmers that write the code themselves and still don't understanding it...
    – hplbsh
    Jan 15, 2011 at 4:54
3

There is a common situation where you basically NEED to do it to be productive.

Any technology unfamiliar to you is hard to learn unless you have a working example to start with. Hence you copy and paste that to have something that actually runs, and then start tinkering with it.

1
  • 2
    Correction: There is an actual beleif where you basically think you NEED to do it to be productive. Hence you copy and paste your way to release something that somehow works and spend enternity suffering your way to repair the damage.
    – Newtopian
    Dec 14, 2012 at 15:52
1

I have so many feelings about this topic, and I can't honestly say any of them are entirely objective.

There are many arguments for cutting and pasting other people's code into your application. Some of them may make sense, some may not. For instance, if you've got a method from someone's blog that takes an input and runs some complicated mathematical algorithm that's way outside your mathematical abilities and spits out a result - that's an argument for cutting and pasting - get the author's permission to use their code and credit them where due - it's the honorable thing to do.

There are arguments for not reinventing the wheel - again, this makes sense, in theory. But if you don't take the time to become intimately familiar with the code you're cutting and pasting, you don't know if there's a better way of solving this problem, you don't know if there are bugs in the code. What if the wheel you're pasting is broken?

There are arguments for speed and efficiency - you build up a library of other people's code that you've ripped off, stolen, plagiarized or otherwise, come to think of it, you may never even need to know how to program beyond Frankensteining some application together out of reclaimed parts.

There are times and places where I deem this behaviour completely acceptable. For hacking together quick throw-away tools that aren't designed for longevity but to get a task done, right now by hook or by crook. For the purpose of prototyping and studying concents, to learn and advance in a theoretical context I think this is completely fair game.

Cutting and pasting other people's code is plagiarism - if you have their blessing and you understand the code you're pasting and it fits within the construct of the coding standards for your application, then fine, I will concede it's fair game.

As a professional software engineer, I am being paid to maintain a standard and a code of ethics. I'm not being paid to steal, plagiarize or infringe on other people's copyright putting my client at risk of prosecution. Aside from this, there is a very real risk that when you run said cut/pasted code it has catastrophic side effects.

Not targeting this answer at you John, I know you're very ethically inclined when it comes to topics like this, so this is really just a general rant in the direction of the question itself.

Addendum: That said, I feel that cutting and pasting your own code between projects is quite acceptable - unless it was written as work-for-hire for someone else, in which case you don't own the copyright and you should get the permission of the person you coded it for. I've found that unless the code is pertinent to proprietry functional concepts, most employers are okay with you re-using your own ideas for other clients.

8
  • What's your take on using code from blog posts that solve a specific problem you're having? Is physically copy/pasting the code what you'd consider a breach of ethics or would retyping the solution into your project fall into the same category? Does the size of "borrowed" code (i.e. a complete program/function vs a small snippet) affect your opinion?
    – Adam Lear
    Jan 15, 2011 at 3:07
  • 3
    I feel that if it is on a blog post then the author intended for it to be public, so if it is useful to you then it is fair game. However, I have hardly ever come across code snippets that could be copied verbatim. They usually require a little finagling.
    – Pemdas
    Jan 15, 2011 at 3:37
  • I don't have a problem with code from tutorials or blog posts being used - just understand what it does. Presumably if it was posted, its available. Jan 15, 2011 at 6:11
  • "Not targeting this answer at you John" ... I actually didn't think you were ... well at least not until I read this anyway. LOL Jan 15, 2011 at 7:58
  • I like your comments on plagiarism & completely understanding the code, but do you really think it's more efficient to copy / paste somebody else's code, than to just write it yourself? I find that you will either not fully understand it and have issues later, OR your attempts to fully understand it will take longer than just writing it yourself. KWIM? Jan 15, 2011 at 8:00
1

Given that, in one open source repository, 15 % of all methods are copied from one project to another (pdf), the answer seems to be a clear yes.

0

I find that "integration" team members or those that don't have as much experience with code or in programming tend to copy & paste more often and not understand what they did (getting into the problems mentioned in your question).

I also find that programmers often stay away from cut & paste to their own chagrin because they love code and often reinvent the wheel, just because they want to do it better or learn more.

1
  • +1 for the reinventing. I also find myself a load of time rewriting code from the internet instead of copy pasting. I guess I do that because I am not restricted to deadlines. I can freely learn by my self and I can learn what en when I want.
    – user11317
    Jan 15, 2011 at 21:29
0

If the code is good then instead of copy and paste it should be made into a common library. But people can't be bothered with refactoring and they prefer to have same functionality spread by copy and method.

Instead of having a universal absolute law of copy and paste is good or bad, one should see when to use it.

The pros for copy and paste are : Gets you going fast Cons are : Same code is spread in multiple places and any problem found/solved needs to be solved everywhere, if instead of copy and paste one used it as common library then the update will propagate everywhere. For a small initial investment of using a library instead of spreading the same code everywhere manifolds.

The choice is to whether save a little time initially compared to a lot later, then copy and paste is the way to go, otherwise refactore and put it in a common library.

2
  • I definitely agree about the common library, but should you cut & paste that code, or create it from scratch? Jan 15, 2011 at 8:03
  • The fastest way to import code is by copy and paste but one should review and if needed modify the code before plunking it into a project and forget about it.
    – jimjim
    Jan 15, 2011 at 9:14
0

In most cases, code that you'll find on the net won't fit your exact purposes.

What is see myself doing a lot is copying code from someone, stripping it down to the very essence and then adding code till it meets my requirements. I'll always refactor it to match my naming conventions and coding style.

I personally hate it when I read a tutorial and they start by showing code for a complicated case. Start with the essence and show building blocks to extend the code. If I ever start an own blog, I'll provide people with a commented code example which shows the essence of what I want to do, how you can add functionality/special cases and a fully working example of the basic feature.

Not the answer you're looking for? Browse other questions tagged or ask your own question.