views:

223

answers:

4

I just found myself copying and pasting the same code twice.

Right now I have one function that I want to share between two source files. It will pass the same variables from both source files. If I don't want to "repeat myself" would this be the best course of action? If both files have other functions that are separate should these reside in the library file, or as they are in the source file? How do you decide if a class is appropriate? How do you determine when to start splitting things apart?

+4  A: 

Don't repeat yourself. Create an include file with the shared function.

anthony
+2  A: 

You should read a Object oriented analysis and design book. These question are about the OO principles.

Your better option in my humble opinion is taking a book like: HF: OOA&D. I readed it and it answer ALL yours questions.

If 2 files are repeating some code, you should get that code out in a function and use it en the 2 files.

Remember that a class has only one responsability, then, you have to put that function in the right place, for example, if it is a utility code, you cant put it in a utilities module.

When a class is appropiate? You have to do some domain anaylisis on your problem's use cases and looking at the nouns that are the candidate classes of your program.

How to determine that? You have to do some analysis and design of your problem before codding.

In short, I recommend you that book, it's all you need :PP

Jesus Rodriguez
+2  A: 

Agree with above answer - Don't repeat (haha the irony of having repeated someone elses answer!).

Regarding classes vs functions, I wouldn't say there is a definite answer.

I've heard arguments that we should sometimes forego OO functionality for the sake of speed, but I think that matters little with the speed of computers nowdays. I personally always prefer classes as soon as the app/site starts getting anything bigger than very small. For example, you might use two functions together to achieve a certain result on a page. Reusing that would then mean you have to a) call both again or b) write a third function to call the other 2. In this case a class starts to look more appealing

Classes are easily testable esp with mocking frameworks. Classes also make it easy to serialize an object holding a lot of data

David Archer
+1  A: 

A while ago, I read an article (I believe on Coding Horror, but correct me if I'm wrong) about copy/pasting code. Basically, if you're using copy/paste a lot in your code, you should really consider making it into a function, which is good practice since it allows you to simplify your code, not only making it more optimized, but also making it easier for other developers to follow along with.

Vestonian