patterns to avoid code duplication

Aaron Wang

Rule of the thumb: Don't Repeat!

  • Hard to read, all seem similar, are there any differences or not? 
  • Too much details are spread everywhere, can not find the key point, headaches!
  • Hard to change, you might change some of them, forget the others, cause inconsistency, therefore bugs
  • No one dare to change, so more duplication, everyone tends to write new code instead of reuse, it will get worse and worse
  • It's literally the biggest enemy to code maintainability

Extract small functions

  • Clean functions
  • Utility functions & classes

class inheritance

  • Put common things in base class, while children can override if needed
  • Template method pattern
  • Use polymorphism to avoid if/else
  • Don't go for it just for code reuse, only when it's appropriate

class composition

  • When inheritance is not right

ASpect oriented programming

  • Programming is about data process, imagine a pipe of data you can filter, intercept
  • Common cases:
    • Authentication check
    • Error handling
    • Logging
    • i18n

Examples

Patterns to Avoid Code Duplication

By Aaron Wang

Patterns to Avoid Code Duplication

  • 1,051