views:

80

answers:

3

Which principles, code qualities, practices, aproaches, language or framework features help you to reuse effectively functions, classes etc in wider range of cases. All of the situations are interesting: either you can modify both implementation and interface of the code to enable/improve reuse, or only implementation, or nothing at all. The key indicators of effectiveness of reuse are (as for me):

  • how much it reduces effort for implementing and maintanance
  • quality of application does not degrades
  • how much complexity is reduced

(all comparing to reimplementing from lower level).

PS. If possible please specify one factor per answer with description how it helps in your case.

+5  A: 

It's a classic - low coupling and high cohesion. If a module or function performs one specific task and has few or no dependencies, it will be much more reusable (as it will fit into a larger variety of situations) than if it performs multiple tasks, has lots of side effects, requires other modules, etc.

danben
+3  A: 

Test Driven Development. For code to be easily unit tested it should:

1) do one thing only

2) have as few dependencies as possible

3) often have those dependencies passed in (so that they can be mocked out)

By an amazing coincidence these factors also make for reusable code. Actually it is not coincidence - the best way to have reusable code it to ensure it is used by at least two callers as early as possible. Code created with TDD starts life with two parents - the code under construction and the unit tests, so it is being reused from the start.

TDD has many other advantages apart from reuse - it gives you automated tests for all your code, it acts as example documentation for how to use the code, and it makes refactoring safer. Writing code with TDD can take longer than writing code without tests, but you will often make it up by needing far less time debugging.

Dave Kirby
+2  A: 

Functions should have no side-effects, essentially. Don't use global variables - pass what a function needs in arguments, and pass function's output as return value

Ink-Jet