How do you make code reusable?

Silvercode picture Silvercode · Nov 6, 2008 · Viewed 40.1k times · Source

Any code can be reused in a way or an other, at least if you modify the code. Random code is not very reusable as such. When I read some books, they usually say that you should explicitly make the code reusable by taking into account other situations of code usage too. But certain code should not be an omnipotent all doing class either.

I would like to have reusable code that I don't have to change later. How do you make code reusable? What are the requirements for code being reusable? What are the things that reusable code should definitely have and what things are optional?

Answer

Galwegian picture Galwegian · Nov 6, 2008

See 10 tips on writing reusable code for some help.

  1. Keep the code DRY. Dry means "Don't Repeat Yourself".
  2. Make a class/method do just one thing.
  3. Write unit tests for your classes AND make it easy to test classes.
  4. Remove the business logic or main code away from any framework code
  5. Try to think more abstractly and use Interfaces and Abstract classes.
  6. Code for extension. Write code that can easily be extended in the future.
  7. Don't write code that isn't needed.
  8. Try to reduce coupling.
  9. Be more Modular
  10. Write code like your code is an External API