Subscribe

Close

Thank you for visiting!

Please consider subscribing to the RSS feed or following me on Twitter.

Rules of Progamming: Don't Repeat Yourself

If you have to write the same code or almost the same code more than once in a project, there's something wrong.

DRY (Don't Repeat Yourself) is one of the most important principles in software development, aiming at reducing code, making it easier to maintain code.

Next time, if you find yourself copying and pasting code, ask yourself: can I refactor this code and make it more efficient?

Rule #6 of programming:

Don't Repeat Yourself

Hey, you can even get this on a shirt!

Comments

Love the DRY principle!

DRY is perhaps not always the best option. DRY sometimes lead to unnecessary complexity in the code.

Se this video, 28:50 minutes in:

http://vimeo.com/17151526

@Mathias: Thanks for sharing! I attended that presentation too. 48 minutes well spent!

Regarding the DRY principle - it's good to follow it most of the times. Sometimes it's better to just duplicate code and get on with other problems instead.

Now this could turn into a lengthy discussion.

I'm on the fence, I must admit.

If you need to duplicate your code because you see a scary dependency come barrelling your way then you should probably take a look at what you're creating a dependency to.

That's probably the source of the problem. The method/class/something you're creating a dependency to is most likely too complex. Simplify. See Martin's KISS post. ;)

E.g. a dependency to method IDoAlotOfStuffAndReturnArbitraryResult() will be a pain to maintain and will create scary dependencies where you are better off duplicating your code. Which in turn leads to management issues and so forth.

Now, refactor IDoAlotOfStuffAndReturnArbitraryResult() into DoOneAndOnlyOneSimpleThing1() and DoOneAndOnlyOneSimpleThing2(), split the dependencies and receive maintainable code.

I'm on the fence, as I said, though. Because reality usually swings around and bites you in the behind.

Great suggestions, Daniel. You should blog even more about architecture and thinking in the programming world!

This also touches a third blog post in my Rules of programming series: "Always try to improve code you're working on": http://blog.dileno.com/archive/201012/rules-of-programming-always-try-to-improve-code-youre-working-on/

To the top