3

I have been reading about the DRY principle. Though it seems so easy, I am having difficulty in understanding how we actually achieve it in any project, be it a web application or Swing.

Maybe a few examples will give me a lead and help me in developing my thought process.

I have tried to search on Google, but I could not find anything suitable.

3
  • 3
    The principle is simple enough... don't repeat the same logic in multiple places. It's achieved by, well, not repeating the same logic in multiple places. Do you have an example of where you're having trouble applying it? (Side note based on your comment: Voting is anonymous and users are not compelled to comment on votes. It's best not to take it personally.) Commented Sep 16, 2013 at 15:37
  • 3
    @David I understand your point.but people could be more humble and at least comment that Question is too abstract So that at least it could be improved.Instead just thinking that the this guy is moron and down vote the Question and runaway .No body is stopping any one from down voting anyway .You could downvote it after suggesting also. Commented Sep 16, 2013 at 16:01
  • Nothing fancy in it. It is very obvious and clear with its full form. DRY -- Do not Repeat Yourself. Try to use whatever is present. In programing this principle is used to avoid code duplication and code reusability Commented Mar 12, 2018 at 6:13

1 Answer 1

21

DRY is nothing that requires examples. If you are copying and pasting blocks of code from one method, function or block of code to another, then you are in violation of DRY.

Very simply, DRY tells you to move that code into a reusable unit: either into a function or method or macro, or other mechanism relevant to your programming language. If you have places in your codebase where you clearly have very similar code (even with minor variations) then you should be looking to refactor that code to make it DRY.

"Don't repeat yourself!" == "Don't write the same code repeatedly"

Sign up to request clarification or add additional context in comments.

3 Comments

by reusable unit ,could it be a new class itself?If the repeated code is to be removed but there is no similarity between the objects.What should I do in such case?
@Niks for example? A lot of answer could be done if you are not precisely, you could use generics perhaps.
Yes, the reusable unit could be an entire class, or an abstract class, or any other component of reusability. If you're using a Dependency injection framework then certainly you will have entire classes. Where oop is concerned, sophistication in your design starts to veer into the area of common design patterns, described in the Gang of 4 book as well as many other language specific books. This site is also a great free resource: oodesign.com

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.