copy and pasting code

Hi,
I think that one of the things that makes a programmer lazy to properly program OO is the tendency to copy and paste a lot just because it seams easier at the time. How do you prevent copy and pasting a lot and building nice clean code?
Any tips or tricks would be helpful because sometimes I feel it can be a flaw of mine.

If you EVER copy and paste code (within the same project), just cut instead and make a new function with that code encapsulated. Take the extra few minutes to add any parameters that may be needed for it to behave as it must on each case.

Also: INHERITANCE. Please use it :slight_smile:

What Tharsman said.

I just DON’T copy-paste, because I know it will bite me later. I usually do cut/paste OR use refactoring. A lot of professional coders use re-sharper, but I find the built-in refactor tools more than enough.

Check out composition over inheritance, sometimes it can really save your bacon :slight_smile:

There’s two kinds of copy/pasting code, and both are usually bad. The first is what you mentioned, copying code within in the same project because similar functionality is needed elsewhere. It’s usually better to abstract it into a method or base class and reference it from both places.

The second kind is copying code from another source into your project, usually without trying to understand how it works. This is really, really bad. The only reason you should EVER do this is because it’s an algorithm beyond your abilities and comprehension, and you should still figure out the inputs and outputs enough that you can put it into a method of its own, along with a comment that links to the source.

Also, +1 for composition. Inheritance is overrated.

Copy and pasting is awesome. Well done - you’ve achieved the first principle of programming:

  • Be Lazy

However, as others have mentioned, there are plenty of situations where copy/pasting isn’t good. This is generally when you are building duplicate functionality.

Luckily the language/s contain several features to help you:

  • Loops
  • Classes/Structs
  • Inheritance
  • Generics

All spring to mind.

Take a look at this thread, tell us which is easier to read/maintain/debug/edit - the OP or my re-factored version [down a few posts]. Even using the loop, separating functionality and removing parenthesis makes it’s a ton easier to work with.

I once saw a guy (well not the guy but his code years later) that unrolled a loop into copy-pasted code.

Instead of doing a simple For loop, he literally incremented the variable with a +1, did all the code, and then copy and pasted that entire block. Worse, he did tiny fluctuations in some blocks that would had been easily handled with a simple X = (X + 1) % xMax

AND he kept adding more and more every time a new option to the client’s categories list was added. And don’t get me started on his database design and entire ignorance on normalization concepts… ugh… … ok I stop here before I derail too much :stuck_out_tongue:

+2. In fact, I’d go so far as to say 99% of programmers (who use it) don’t use inheritance properly. There are good reasons to use inheritance, to be sure. But you should always go for composition first, inheritance second. Unless you have a good reason, you should be using composition, not inheritance, in most cases.

Revisiting here, I got to say I had never heard the term “composition” before this thread. I had to google it and not sure if I got the right answer. Big reason I didn’t hear the term before, I guess, is I studied in Spanish, but even then cant remember any professor naming that practice with any special terminology. Heck, at the time the C++ standard had not been fully finalized and Java was a “coming soon” and overly hyped piece of technology! My… I feel old…

Anyways, correct me if I’m wrong, but “composition” is simply referring to know when to instantiate a class inside of another class instead of inheriting from it? Like:

A car is a vehicle (inheritance)
A car has wheels (composition)

?

Please, let me know if I am wrong about what composition actually means.

IF that is what composition means then I stick to my original comment but have to expand:

I seen projects where a developer will copy and paste a critter core logic across many different critter scripts. I feel a more proper way is to create a Critter script that has a lot of protected functions and then have various critters inherit from that base.

I have a class similar to that in Bomber Cat, a Critter that is inherited by Cow that in turn is also inherited by different BossCows, each with slight added specialized functionality. The critter base has common stuff like movement logic and HP management, while the sub classes may have expansions like specialized movement logic or conditional invulnerability, etc etc.

Yes, we’re talking about “is-a” and “has-a” relationships (aggregation and composition).

This guy breaks it down nicely :

http://www.publicjoe.f9.co.uk/csharp/tut/csharp04m.html

Yep, that is exactly right. I guess it really isn’t a very commonly used term.

I don’t mean to say that inheritance doesn’t have it’s place. It most certainly does. But I see programmers misuse is all the time. In my opinion, the default position should always be composition, and only go to inheritance if you have a specific reason to do so.

I guess the main reason I don’t really like inheritance so much is that I find it difficult to read. Coming from a C++ background where multiple inheritance is allowed (and I realize that is not the case in C#), it can get very tricksy to find the routine you are after. e.g.

class ClassA : public Class B, Class C {…};

class ClassB {…};

class ClassC: public Class D {…};

suppose that set up, and somewhere in ClassA somebody calls a method SomeMethod(); I need to go read that method because I need to know what it does. So I look in the header file in ClassA. Hmm, not there. Okay, it must be in one of the inherited classes. I look in ClassB. Hmm, not there. Okay, ClassC. Ah, there it is, great. But notice how long it took me to track it down? Not such a big deal if it’s just the one case, but I often spend many many hours going through other people’s code (it’s a part of my day job), and that sort of thing gets to be a real pain in the ass after a while. You know? And it gets worse when they start trying to get clever and overload the function in the various classes. Now there are multiple instances of that function and I have to figure out which one the compiler is really calling.

Contrast that with composition. The method set is
class ClassA{ ClassB BInstance;};

and the call is

BInstance.SomeMethod();

See how easy that is? I know exactly where to find that function.

But anyway, that’s coming from the perspective of a person that often has to manually refactor other people’s code, so my perspective is skewed. I realize this gets into religious war territory, and everyone has their opinion. That’s just mine :slight_smile:

Hmm interesting. I never seen this philosophical ground before (Inheritance vz Composition.)

I actually can see your point on inheritance potentially being a pain in the a$# to debug, I have fallen victim of my own code forgetting where something was being called. I attempt to add commented debug statements that log out where the function is being called, and comment them out with an easy to replace key (like DEBUG.LOG(‘classname.functionname.enter’); and keep them commented out and de-comment them when I’m trying to track something down, but admit I very often get lazy to or rushed and entirely forget it.

But there are way too many cases where I can see some one start a composition just so it’s easy to “fix” later if needed but then end up with ackward limitations. Like, for example:

StandardCarWheel (has Rim, Rubber, Rim spins and wheel spins with it)

Then some one makes:

WoodenWheel (has WoodRim, metal around rim, and wheel spins with it)

(I know the example is not the best but bear with me)

Now you need flexibility for some reason to give the player or designer the ability to select any type of wheel on any vehicle. Since both classes share no common parent class, you cant just define 4 wheel classes to hold any possible wheel. Had it been a wheel class that was inherited to 2 different types of wheel, then you would be able to hold the wheel on a parent class variable.

Not saying composition is not important, I think its extremely required, but it sounds like both are vital parts of object oriented programming. After all, the most basic example I think programmers are shown at school is the car and trucks are both vehicles, and vehicles have wheels. Wheels being a class of their own, and cars and trucks being sub class of vehicle (I would say in this case they would have a flexible array to hold the wheels, since some may have 4 and others up to 18), etc etc.

In game development we try to mimic so many real world objects, that a combination of inheritance and composition seem to be extremely vital.

I saw this blog post today that is related to this thread.
http://enemyhideout.com/2012/03/01/mistakes-ive-made-as-a-programmer-inheritance/

A good video by Ben Garney:

What’s mostly going wrong here is that inheritance is used as a way of not duplicating code or making code re-usable.
That’s not it’s intended use.
Inheritance is intended for a hierarchical structure (like a family tree) where objects inherit characteristics from their parents.

E.g. All physical objects have mass –
All movable objects have speed and direction
a car can move therefore it inherits from ‘movable’ which inherits from ‘physical’
A car may also have wheels, but how does that fit into your tree? Not all other moving objects will have wheels, so here composition (or interfaces) may be more useful to you than inheritance.
If a method isn’t needed by a child object, then your inheritance is all wrong. In my example, all cars need to comply with ALL the laws of movable objects and pysics.

A good code architect must know when to use each feature of the language.
It’s best to design your class layout before you begin coding- this will minimise the amount of work you have to re-do during your project.
Think of it this way:
By the end of your project, you will have a full class structure anyway.
Any changes made to your class can structure affect large amounts of code.
I’ve seen huge projects where the architects simply give class diagrams to their horde of programmers who simply flesh out the methods; and all the pieces just fit together in the end because the design was well thought out first.
I would estimate that this method cut down development time by 50%.
(Btw, 21 years experience).