Skip to content

Instantly share code, notes, and snippets.

@paulghaddad
Last active August 29, 2015 14:14
Show Gist options
  • Save paulghaddad/c6821e21a57ff8e4af47 to your computer and use it in GitHub Desktop.
Save paulghaddad/c6821e21a57ff8e4af47 to your computer and use it in GitHub Desktop.
Level Up 7: Employs DRY (and knows when to violate it)
1. Name some techniques we can use to de-duplicate code.
- To remove multiple representations of information, a code generator or filter is often useful.
- Remove duplication between comments and code by eliminating unnecessary comments and writing self-documenting code.
- Since documentation and code representation are two instances of the same knowledge, generate documentation from the code itself (using a tool like RDoc).
- Understand which attributes are mutually dependent on others, and make them calculated. For instance, if a Line class has three attributes, starting_point, ending_point and length, the third is duplicated knowledge. It can be calculated from the first two in a separate method.
- Make it easy to find and reuse components across a system; this allows a team to avoid building them from scratch. Otherwise, different implementations of similar functionality represent duplication of knowledge.
- Refactor using "Extract Method" for duplication in the same class.
- For duplication in views and templates, extract duplication using partials.
- For duplicated conditional logic, polymorphism can be used.
- Follow the Single Responsibility Principle. This will result in classes that can be more easily reused across the program instead of duplicating similar implementation details across many classes.
3. Dry code is a virtue, but sometimes we go too far. Show an example of being too dry, and how to counteract it.
There is a difference between code that has knowledge duplicated in the system and code that has incidental duplication. In the first case, DRY should be used to eliminate the duplication. In the second case, code may appear to contain the same knowledge, but in fact they are independent. For example, methods to calculate the next Mother's and Father's Day may share some common logic. But they are distinct. If we try to DRY out the code, we may get a method called next_parents_day that is not only more complex but is separate from reality. In cases like this, DRYing code leads to more complicated code that doesn't model it's domain accurately; it's best to avoid de-duplication in cases like this.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment