Is copy-and-paste coding ever acceptable?

2020-08-09 14:22发布

It's generally accepted that copy and paste programming is a bad idea, but what is the best way to handle a situation where you have two functions or blocks of code that really do need to be different in just a few ways make generalizing them extremely messy?

What if the code is substantially the same, except for a few minor variations, but those few minor variations aren't in things that are easy to factor out through either adding a parameter, template methods, or something like that?

More generally, have you ever encountered a situation where you would admit that a little copy-and-paste coding was truly justified.

\"骚年 ilove
2楼-- · 2020-08-09 14:51

The best way (besides convert into common functions or use macros) is to put comments in. If you comment where the code is copied from and to, and what the commonality is, and the differences, and the reason for doing it... then you'll be ok.

3楼-- · 2020-08-09 14:52

If you find that you have functions which are mostly the same, but in different scenarios require slight tweaks, it is your design that is the problem. Use polymorphism and composition instead of flags or copy-paste.

4楼-- · 2020-08-09 14:53



You could post the code in question and see that it is easier than what it looks like

The star\"
5楼-- · 2020-08-09 14:54

I've heard people say the will copy and paste once (limiting duplication of code to at most two instances), as abstractions don't pay off unless you use the code in three places or more. () Myself, I try to make it a good habit of refactoring as soon as I see the need.

6楼-- · 2020-08-09 14:54

Ask this question about your functions

"if this small requirement changes, will I have to change both functions in order to satisfy it?"

7楼-- · 2020-08-09 14:54

If it is the only way to do it, then go for it. Often times (depending on the language), you can satisfy minor changes to the same function with an optional argument.

Recently, I had an add() function and an edit() function in a PHP script. They both did virtually the same thing, but the edit() function performed an UPDATE query instead of an INSERT query. I just did something like

function add($title, $content, $edit = false)
    # ...
    $sql = edit ? "UPDATE ..." : "INSERT ...";

Worked out great -- but there are other times when copy/paste is necessary. Don't use some weird, complicated path to prevent it.

登录 后发表回答