quinta-feira, novembro 01, 2007

How not to write code: The evils of duplication

I had to do some maintenance on some old php code and saw the following code:

before

Just by looking at it you can see 3 things:

1 - Everything is duplicated
2 - It was copied and pasted.
3 - The field names sux.

Well, guess what, I wrote that code. period.

But now when I look at it, it is disgusting. I'm violating the DRY (Don't repeat yourself) principle and also suffering from the evils of duplication, because I needed to add one field in that select, and if I didn't refactor I would have to add the field 3 times!

But as I'm sucking less now I took some minutes and refactored the code, here is what the code looks like after a quick and little refactoring:

before

Still not perfect, but way better.