Hacker News new | past | comments | ask | show | jobs | submit login

Though point 4 should be rewritten as "If you find yourself writing the same thing twice, DO be lazy and carry on, put the code in a single place and call it from where you need it."



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.


I don't really understand why people think that copy pasting takes less time than making a new function.

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.


I doesn't usually happen like that for me. More likely, I stumble on a point where I have to reuse part of an old code, but with slightly different goals, or with some steps added/removed in the middle.

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).


> New Function Cut the code. Place inside function declaration. create call to function in old and new places.

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.




Consider applying for YC's Spring batch! Applications are open till Feb 11.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: