22 ms·
You know, sometimes duplicating code is just better. I've been around long enough to see many attempts at refactoring to share code! crash and burn. The hoops a
by titzer 9y ago
You know, sometimes duplicating code is just better. I've been around long enough to see many attempts at refactoring to share code! crash and burn. The hoops and complexity that some people go through to DRY (don't repeat yourself) are worse sometimes than the cost of maintaining two copies.
- kaeluka 9y agoCode duplication can be seen as a "defensive copy". If you duplicate code, the original version can be changed without breaking the copies. Disclaimer: I'm not making a value statement here :-)
- sanderjd 9y agoIn an ideal world, what you want is more like copy-on-write. Share the code until one of the clients of that code needs a change that the others do not, then copy it. In reality, what happens more often is an accumulation of different functionality used by different clients. Copying "defensively" as you suggest can help avoid that problem, but it has the opposite problem of requiring changes to all copies when all clients want the same thing. In my experience, this is the problem more likely to lead to painful mistakes. There is no silver bullet...
- goatlover 9y agoYou mean like prototype-based inheritance?
- sanderjd 9y agoI don't think so... I'm talking about copying the code itself.
- whathaschanged 9y agoSo ctrl-f and ctrl-v using the diff as needed? I wonder if the man hours wasted on hunting through someone else's code to figure out the bajillion abstracted functions are doing when you are trying to make a change outweigh the minor inconvenience of copying and pasting changes are? Yes the latter introduces more opportunities for errors, but are they more than knowing all your dependencies and ensuring your changes don't break their expectations? Unit tests are only as useful as the man who knows the future.
- sanderjd 9y agoThat's basically what I'm saying: it's unknowable whether copying and pasting and needing to keep all the copies up to date in the future will result in more or less work and bug fixing than re-using code. I think the best solution is for experienced developers to make an educated guess on a case by case basis. But you can't write that into a generic principle.
- zbentley 9y agoI don't think prototype-based inheritance (or monkeypatching) is any better at avoiding duplication than "regular" Java-style inheritance, and both will only help avoid certain kinds of duplication some of the time. If you need to modify a small part of a class's function, there's typically no way in a prototype/traditional inheritance language, to say "like the function from the parent class, but with these 5 lines different". Inheritance of any kind is a handy tool to help with the "whole class files full of pages of identical code with one different method" problem, but a) that's not the cause of a lot of duplication out there, b) you still have to know/care to implement the inheritance, and c) it can come with its own struggles, a la tight coupling to implementations/classes you may not fully control. This isn't a pro-OO or anti-OO screed; just pointing out that inheritance as a means to DRY up code is a limited solution at best.
- usrusr 9y agoEven with "copy on write" there would still be the problem of wether to copy before write or not: requirements for usage A change because someone recently thought hard about that part. Usage B is most likely not on anybody's mind right now andchanging that is quite some effort. It's a problem no matter wether you copy, DRY or something in between. Maybe some of our processes, language and experience from the version control space (branch, merge, rebase, upstream...) could be ported over to the reuse vs duplication problem. But when you layer that with the conventional use of those concepts in version control, the result would be quite the multidimensional mindbender. With that as a hypothetical baseline, simply guessing a good compromise between abstraction and duplication and then dealing with the consequences suddenly does not seem that bad a fate.
- kaeluka 9y ago> In an ideal world, what you want is more like copy-on-write. Share the code until one of the clients of that code needs a change that the others do not, then copy it. Good point. The problem with that is, of course, that you may not be aware of others existing. > There is no silver bullet... +1
- naasking 9y ago> The hoops and complexity that some people go through to DRY (don't repeat yourself) are worse sometimes than the cost of maintaining two copies. The number of bugs are proportional to the lines of code, this is undeniable from empirical data. Ergo, fewer lines of code will tend to yield fewer bugs. So if your code is literally the same, there's no reason not to extract it into a function. That said, the moment you have to start adding parameters in order to successfully factor out common code, ie. to select the correct code path taken depending on caller context, that's when you should seriously question whether the code should actually be shared between these two callers. More than likely in this case, only the common code path between two callers should be shared.
- dllthomas 9y ago> So if your code is literally the same, there's no reason not to extract it into a function. If the two pieces of code are likely to change in different ways, for different reasons, that is a strong reason not to extract it into a function even if they happen to be character-for-character identical for the moment. Less code means fewer bugs, but that doesn't mean I should be working on the gzipped representation.
- naasking 9y ago> If the two pieces of code are likely to change in different ways, for different reasons, that is a strong reason not to extract it into a function even if they happen to be character-for-character identical for the moment. The future is much more malleable than your immediate needs. But even if your future turns out to be true, the code you need to refactor is then already extracted to a function, so you can easily duplicate that function, make your localized changes, and change the callers to the new function. So this is still the best route. > Less code means fewer bugs, but that doesn't mean I should be working on the gzipped representation. Don't be absurd. gzipping doesn't preserve your program in human-readable form. Extracting code into a reusable function makes your program more human readable, not less.
- falcolas 9y ago
- justicezyx 9y agoI am pretty sure the crgoculting testless bloated code dismayed the incompetent refactorer. This is not a proof of benefit of duplication, it's a proof of the low quality of the legacy code.
- ajmurmann 9y agoSandi Metz said in one of her talks that wrong abstractions are worse than duplication and we just tell new developers about duplication because it's the only thing they understand. Strongly agreed.
- stcredzero 9y agowrong abstractions are worse than duplication This needs to be given a catchy phrasing and spread all across developer communities! WTD == Worse Than Duplication? WAAW == Wrong Abstractions Are Worse?
- jonahx 9y agoIt's a great principle and I reference it frequently, but as a catchy buzzphrase it has the potential to do as much harm as good: it's easy to abuse as an excuse for copy paste programming. Duplication is still bad, and correct abstractions are still good.
- djur 9y agoSee also "premature optimization is the root of all evil", which I occasionally see stretched to include any kind of thinking about the performance characteristics of your code, even down to basic design decisions like data structures or algorithms.
- grandalf 9y agoGreat point. I've found that most codebases have some abstractions that work very well and others that work less well, and simply having awareness of this can help make the code far more readable. For instance, one might say: "The way x is implemented works, but it's not quite the right abstraction, here's why". That is way more informative than saying it's simply the wrong abstraction or considering it good enough and ignoring its deficiencies.
- gcatlin 9y agoPremature abstraction is the root of all evil.
- pault 9y agoThe issue comes from trying to DRY the code before the requirements and functionality are well defined. If you're doing major refactoring before you have something in production it's just premature optimization.
- geofft 9y agor0ml gave a good argument for duplication over abstraction in his Debconf talk this year: https://debconf17.debconf.org/talks/194/ https://debconf17.debconf.org/talks/194/ (video, I'm not sure if there's a transcript, but if you're bored on a Thanksgiving, I would recommend watching the whole thing)
- quotemstr 9y agoI like to say that programming is not an exercise in Huffman compression. Not all structurally similar chunks of code should be unified: sometimes these chunks are _semantically_ different, and unifying them would create a false and confusing commonality.
- nikbackm 9y agoThat's what copy-on-write is for. ;)
- gnuvince 9y agoI mentioned a few months ago in a similar thread that I now actively try to recognize when I'm creating an incomprehensible 300-line "abstraction" in order to avoid copying four line of code.
- usrusr 9y agoDid you ever succeed? ;) I sometimes notice but just can't stop it. The next step is usually a desperate attempt of painting that pig with documentation.
- novembermike 9y agoOne of the problems is that people hear "DRY" and they don't hear "Every piece of knowledge must have a single, unambiguous, authoritative representation within a system", which is the actual idea. They don't even share any words. The actual idea is really cool and demands correct abstractions, DRY is about making things not look the same.
- laythea 9y agoI've seen this also. The amount of hoops and jumps people go through in order to abstract something can be ridiculous, ending in code only the author can understand. Bad for business!
- usrusr 9y ago...that only the author can understand, and not after being done writing. But still, good abstractions are much better than duplicated code, yet bad abstractions can easily be worse. "Minimize both duplication and bad abstractions" should be something everybody can get behind, even if only because it leaves all the details open.
- dragonwriter 9y ago> "Minimize both duplication and bad abstractions" should be something everybody can get behind, even if only because it leaves all the details open. Leaving all the details open means the slogan is content-free. Why would anyone get behind it?
- usrusr 9y agoUsually it happens when people put their favorite ideas into the blanks and do not realize that others could fill them in a different way.
- fooblitzky 9y agoThese days I prefer SPOT (single point of truth) over DRY. I find DRY tends to encourage people to use hideously complicated abstractions to avoid code that even looks similar. It's also way easier to refactor some duplicated code than to try and untangle complicated abstractions. SPOT more accurately identifies the pain point of duplicated code - if there is an algorithm or configuration value that needs to be specified, than that should just be in a single place, everything consistent and easy to change.
- HelloNurse 9y agoGood name, it helps with distinguishing things that are meant to be the same (e.g a single implementation of an encryption algorithm, used in various places) and things that are distinct but accidentally identical (e.g. permutations in different stages of that algorithm).
- gowld 9y agohttps://en.wikipedia.org/wiki/Don%27t_repeat_yourself https://en.wikipedia.org/wiki/Don%27t_repeat_yourself > The DRY principle is stated as "Every piece of knowledge must have a single, unambiguous, authoritative representation within a system". How is SPOT different?
- dllthomas 9y agoI'm unclear as to whether the parent is preferring the name SPOT for the same concept, or preferring what they are presenting as a different concept (which, as you note, seems to match the original definition of DRY).
- zaarn 9y agoI think SPOT is different in that DRY has become misunderstood, so the "Single Point of Truth" brings the proper point across a bit better.
- kibwen 9y agoAgreed that fanatical adherence to DRY is a mistake. I did this when I was first starting out: any code that looked similar at all would be factored out into a new hyper-specific function, regardless of how unrelated the original pieces of code were. But this introduces extreme coupling between components that have no right being coupled, and makes evolving the code a nightmare (suddenly all your DRY-borne functions grow immense lists of configuration parameters to account for unforeseeable differences). At the same time, let's not take this dogma too far in the other direction. Repeating oneself is still undesirable, but DRY-related refactoring should focus on behavior and intent, not on how the code looks. And abstractions are still good (they're how we get anything done at all!), but leaky abstractions should be avoided, indirection-via-abstraction should be minimized, and we should be vigilant against extreme and overeager overapplication of abstraction (insert your blub joke here).
- antonvs 9y agoBalancing these kinds of constraints - how much and when to DRY vs. copy - is a big part of what engineering is about. It also needs to take into account factors like available budget of time and money, capabilities of the team working on the code, etc.
- gowld 9y ago> But this introduces extreme coupling between components that have no right being coupled, and makes evolving the code a nightmare (suddenly all your DRY-borne functions grow immense lists of configuration parameters to account for unforeseeable differences). * A and B both depend on the same logic X. * You make a shared helper function X * Requirements for A change, necessitating a change to x. * You check if B requires the same change. If yes, change X. If no, fork X into X_A and A_B Now you're staying DRY, and DRY has saved the day by forcing you to think about whether A's change should impact B. If you had prematurely forked X, then X_A and X_B would drift without any sanity check on whether they should.
- andrewingram 9y agoThe question I ask myself is: Are these two things that look the same, actually the exact same problem, and do I expect them to continue being the exact same problem? If the answer is an easy yes, then build your abstraction. If it's no, don't. If it's maybe, leave the duplication in place until you have a clearer understanding.
- ericmcer 9y agoProgrammers seem allergic to the idea that they would have to go through and update several functions that do the same thing. This is mentally a very trivial task though, much preferable to trying to alter some 'clever' dependency. In a super agile environment especially I find DRY practices will quickly build a huge web of garbage.
- mpweiher 9y ago"Premature abstraction is the root of all evil" -- me On the other hand, maybe it also points to problems with our abstraction mechanisms?
- Nicholas7900 9y agoHacking a phone or a computer does not depend on programming language, but exploit the existing vulnerabilities. If you mean by create Windows virus/trojan/malware, them are generally written in Visual C++ (VC++), and you can learn it by buying books for basic knowledge and go to practice. so i think adrian lamo uses c plus or v plus for hacking. I don't know why every one talk about Nicholas Shields, I'm not the only Hacker online, but if you like to know what hackers use i can tell you , to hacking web site for example you need script python or Perl or ruby ... but its not the important part because first you should know what you will do and then it will be easy because maybe you will found some code in the internet like here Exploits Database by Offensive Security , so there is a different between someone who hack by using tools and code already done and someone who found "zero days" bugs and expel hacking. For urgent requests for professional Hack Advice Or Hack Services, You can contact me directly via """"compositehacks@gmail.com""". I'm also trying out a new beta ticketing system, which can be accessed at "Composite Hacks & Co"
- pqh 9y agoDon't abstract it out until it's used in multiple places. Don't abstract it out using a complicated system, like inheritance, when you can use a function in a module. Don't abstract it out if it's superficially similar as opposed to actually the same thing. Regarding the last point: iterators, good abstraction; averaging function, good abstraction. These things never change. But bad abstractions copy things that are only similar in appearance.
- breatheoften 9y agoThe flip side of this occurs when trying to evolve systems with too much copying — particularly when there is not a good way to find where “these things should behave the same” has spread ... I get really nervous when coding up a pattern based on copying when the main reason for the copying is that there _isnt_ a good way to share the logic without a lot of hoops ... copying when I see how I could easily have shared the logic feels like such a safer decision, much easier to justify because I can always see how to refactor later if it proves that the copied pattern really does represent a use that evolves with shared requirements. When I’m put into a situation where I know that I’m only copying because I can’t see a good way for the logic to be shared I feel like I’m setting up an infinite game of bug wack-a-mole as errors due to untraceable synchronization requirements are doomed to reoccur forever as the system changes ... I find these scenarios frequently popping up when using tools with poor composition capacity (lots of build and deployment systems) — “I don’t know how to compose this stuff so I’m just going to copy and will hate this later” is the worst feeling.