Hacker News new | ask | show | jobs
by atas 3180 days ago
Simple technique for preventing bugs like this: don't copy-paste code. If you find yourself copy-pasting code think twice why you even have to do it (DRY principle) and be aware of the potential consequences. Even if some code has to be duplicate, I am forcing myself to just write it from scratch, exactly for this reason: do you really know that you have updated all your data? And yeah, unit tests would help in spotting this and other things. But aren't unit tests a duplication of your code, already?

UPDATE:

Maybe I should have stated my last question differently. I meant that in the context of checking that the data is correct, it would be the same as writing the duplicate code from scratch.

4 comments

Just to play devil's advocate: sometimes DRY code is harder to understand, which makes it harder to see bugs. Whenever you introduce an abstraction to make your code DRYer, you have to remember the law of leaky abstractions. DRY code is a good principle to follow, but not an absolute law.
Yes, and that's why you have to be extra-careful with copy-pasting :-)
Some languages are leakier than others..

As for terse code: a line that's five times as hard to understand might be worth it, if it saves ten. (But I usually code in languages that are famously terse and have watertight abstractions---at least in the correctness sense, even if not in the performance sense.)

> But aren't unit tests a duplication of your code, already? > UPDATE: > Maybe I should have stated my last question differently. I meant that in the context of checking that the data is correct, it would be the same as writing the duplicate code from scratch.

Good units tests, especially for UI entry are difficult to envision. Have a look at https://news.ycombinator.com/item?id=15432567 where I tried to sketch a general way to address this class of problems.

But aren't unit tests a duplication of your code, already?

No?

> But aren't unit tests a duplication of your code, already?

No, as you'd only be specifying the input and output state, e.g. the change of a model's attributes or the correctness of a mathematical calculation. The code that implements the (business) logic of going from input to output state should be part of your application, not the test.