(no title)
asto
|
13 years ago
There is usually an upfront cost of time and/or effort. The choice comes down to copy-pasting what you need everywhere or put effort into making a generic function that you can put in one place. If you are working against an impossible deadline, option 1 seems very enticing. In the long run, you are right, the effort is much less to maintain a well thought out codebase.
HarrietJones|13 years ago
Your function may need some refactoring to make sense, but just cutting that block of text out and then calling it in a function can usually be done in seconds.
Copy Pasting: Copy the code. Paste in new place. Change variable names to fit in new place.
New Function Cut the code. Place inside function declaration. create call to function in old and new places.
Wilya|13 years ago
Copy-pasting and just dropping the useless parts is easier than making a new function, because you have to think about how to make the new function apply to both cases (the easiest way is "well, I'll just put a switch in the parameters and if statements", but it doesn't really lead to better code).
TeMPOraL|13 years ago
And also: decouple code from it's context. Rename variables. Rename the function. Possibly add a new module for it.
Moving repeated code to a function rarely just about relocating a piece of code. Quite often (especially if you have cross-file code repetition) you identify abstraction, which is a Serious Business (TM), requiring at least to think about where to introduce it, how to fit it into existing mental model of the program, and while we're at it, how to make it useful for code that you'll be writing next week, because it would be a waste not to do that now.
It's not that difficult and it's quite rewarding, but it also takes significantly more time than just copy-pasting and carrying on.