Hot answers tagged

129

A common misunderstanding with the DRY principle is that it is somehow related to not repeating lines of code. The DRY principle is "Every piece of knowledge must have a single, unambiguous, authoritative representation within a system". It's about knowledge, not code. LoginPage knows about how to draw the page for logging in. If EditInfoPage knew how to ...


121

If you repeat yourself, you can create maintainability issues. If doStuff1-3 all have similarly structured code and you fix a problem in one, you could easily forget to fix the problem in other places. Also, if you have to add a new case to handle, you can simply pass different parameters into one function rather than copy-pasting all over the place. ...


111

You don't do DRY because someone wrote it in a book somewhere that it's good to do, you do DRY because it actually has tangible benefits. Specifically from that question: If you repeat yourself, you can create maintainability issues. If doStuff1-3 all have similarly structured code and you fix a problem in one, you could easily forget to fix the problem ...


75

If they really are reusable methods / classes, you could write them into a small number of 'Swiss Army Knife' libraries. We do this quite often at my company; we call them framework libraries: Framework.Data - Utilities for working with database queries. Framework.ESB - Standard methods for interacting with our enterprise service bus Framework.Logging - ...


58

The general rule reads "Prefer delegation over inheritance", not "avoid all inheritance". If the objects have a logical relationship and a B can be used wherever an A is expected, it is good practice to use inheritance. However, if the objects just happen to have fields with the same name, and have no domain relationship, do not use inheritance. Quite ...


47

Because DRY will be less work later. DRY: (Don't Repeat Yourself) One function taking an argument. def log(arg): print(arg) C&P: (Copy&Paste) 26 gazillion functions doing essentially the same thing, but with a 2 char difference. def logA(): print('a') def logB(): print('b') ...ad infinitum... How about we update our printing to ...


46

Er wait you're concerned that repeating public LoginPage loginPage; in two places violates DRY? By that logic int x; can now only ever exist in one object in the entire code base. Bleh. DRY is a good thing to keep in mind but come on. Besides ... extends LoginPage is getting duplicated in your alternative so even being anal about DRY wont make sense ...


34

I want to challenge your basic premise, namely that Design Patterns aren't added to the standard library. For example, java.util.Iterator<E> is in the standard library and is an implementation of the Iterator Design Pattern. java.util.Observable/java.util.Observer is an implementation of the Publish/Subscribe Design Pattern. java.lang.reflect.Proxy is ...


32

You're not wrong. It's just psychologically very difficult to convince people of their own limitations. The reason we have invented maxims, guidelines etc. that restrict what we should do is that we have found, over time, that behaving in a particular way leads to more success. Importantly, it will lead to more success even if it doesn't seem so to us at ...


30

In a way, you answered your own question with that remark in the last paragraph: I am starting to think the DRY principle does not apply as much in this kind of situation, but that sounds like blasphemy. Whenever you find some practice not really practical for solving your problem, don't try to use that practice religiously (word blasphemy is kind of a ...


27

The Don't Repeat Yourself (DRY) principle is easy to mindlessly over apply. Keep in mind that the real sin isn't using copy and paste. It's spreading a design decision around in a way that makes it difficult to change that decision. If what you really have is two decisions that just happen to look the same at the moment then everything is fine. You'd be ...


24

One idea would be to wrap it with a function that takes a Func. Something like this public K UsingT<T,K>(Func<T,K> f) where T:IDisposable,new() { using (T t = new T()) { return f(t); } } Then your above code becomes public List<Employee> GetAllEmployees() { return UsingT<Entities,List<Employee>>(e=>...


24

I believe this is a misconception any way I can think of. The test-code that tests production-code is not at all similar. I'll demonstrate in python: def multiply(a, b): """Multiply ``a`` by ``b``""" return a*b Then a simple test would be: def test_multiply(): assert multiply(4, 5) == 20 Both functions have a similar definition but both do ...


23

To me this would be like worrying about foreach-ing over the same collection multiple times: it's just something that you need to do. Any attempt to abstract it further would make the code much less readable.


23

Design patterns are recurring designs which cannot be captured in a class or library. Usually they have to do with how multiple classes interact. The standard library of a language can use patterns just like other code can - eg. the Java IO library uses the decorator pattern. But the decorator pattern itself cannot be captured in a single class or library. ...


23

If changing the sound files for each single grade without modifying the code is the requirement here, I would externalize the configuration (mapping). Create entries in your configuration mechanism (config files or database) which contain the sound file names for each grade. Instead of duplicating the sound files I would rather list the same file name ...


22

Tackling each of these at a time: Regarding the Project Structure This one can be subjective at the best of times, but projects are typically structured by logically dividing your code into sub-folders or sub-projects based on their general area of responsibility, or which 'layers' they belong to. For example, Models, Views, Controllers, Core ...


21

I disagree with the accepted answer for many reasons. In my experience, when I see "miscellaneous" libraries like the accepted answer, they're an excuse to reinvent the wheel (or not invented here(NIH)) - a far greater sin than violating Dont Repeat Yourself (DRY). Sometimes violating DRY can be a reasonable compromise, it is better than introducing tight ...


20

This is actually a very difficult question to answer and I have found it to be a very controversial subject. As Yannis Rizos pointed out in his answer, having the constraint logic in both the database and the ORM layer would seem to violate DRY, which "can lead to maintenance nightmares, poor factoring, and logical contradictions". However, removing the ...


20

His primary argument was that "he's a good programmer and he can understand and read even the first version fast enough" so he doesn't care if it's written like that or not. If that is his primary argument it may be a sign that he is primarily afraid with being not called a good programmer, or even a bad programmer. IMHO the crucial point here is to make ...


20

The biggest reason against two applications is that you are very likely to have to implement user rights anyway. Presumably you aren't going to allow an advisor to enter notes about students he doesn't advise, or delete important information without uber-admin privilege, or edit information about advisors other than themselves? Once you have this mechanism ...


19

boolean arguments to trigger different code paths in a single function/method is a terrible code smell. What you are doing violates Loose Coupling and High Cohesion and Single Responsibility principles, which are much more important than DRY in precedence. That means that things should depend on other things only when they have to ( Coupling ) and that ...


18

it is just called duplicate code - I don't know of any more fancy names for this. The long term consequences are as you described, and worse. Of course, eliminating the duplication is the ideal option if only possible. It may take a lot of time (in a recent case in our legacy project, I had several methods duplicated across more than 20 subclasses in a class ...


18

By using inheritance, you will end up with something like this, but class names will lost it contextual meaning (because of the is-a, not has-a): Exactly. Look at this, out of context: Class D : C { String age; } What properties does a D have? Can you remember? What if you complicate the hierarchy further: Class E : B { int numberOfWheels; } ...


18

DRY absolutely does not mean "use minimum number of lines possible", or "do not write code that looks like other code" DRY refers to having code that does the same thing in two different places. But same doesn't mean "code looks the same" but rather "does the same conceptual task". How the code looks is irrelevant, what it does is what is important. Don'...


17

child classes use different types, the calculation varies a tiny bit from class to class. First and foremost thing is: First clearly identify what part is changing and what part is NOT changing between the classes. Once you've identified that, your problem is solved. Do that as the first exercise before starting the re-factoring. Everything else will fall ...


17

It depends. Assuming that the subject (and not the sender, for instance) is the only "repeated" parameter here, I'd turn the question back on you: If the subject text changes in one place, does it necessarily change in both? DRY isn't so much about eliminating the amount you copy+paste. It's actually quite easy to copy and paste! What we aim to avoid is ...


16

Because, applied to your example: + readability Less code often translates to less noise. (not always...) + flexibility If you ever had to change the behavior of the doStuffX, you'll want to kill yourself or whoever wrote it, + extensibility If you had extracted the distinct parts to a data-structure of your choice and then just iterated over it by ...


16

Your guiding principle should be Don’t Repeat Yourself: In software engineering, Don't Repeat Yourself (DRY) is a principle of software development aimed at reducing repetition of information of all kinds, especially useful in multi-tier architectures. The DRY principle is stated as "Every piece of knowledge must have a single, unambiguous, authoritative ...


16

I think this rule of thumb exists because it is easy to get caught into playing "What if..." when designing the code for the first time or after the first duplication. I've encountered severe analysis paralysis in some cases because people started designing functionality that might be needed later. But not needed for the immediate problem at hand. There ...


Only top voted, non community-wiki answers of a minimum length are eligible