Software Reuse Quick Tip #24

November 25, 2009

Tip #24 – Identify common behavior and encapsulate it

Looking for common behavior across classes is an effective way to reuse behavior. When you find yourself cutting and pasting code, take a step back and reflect on the common behavior that is being implemented. If the duplication is due to the same behavior realized in different ways, introduce a new interface. If multiple objects have the same functionality and can derive from a parent object, introduce an inheritance hierarchy.

This can be done in an iterative fashion as well – if you failed to recognize an interface initially that is okay. Look for opportunities to refactor existing code to introduce a new interface. For example, you can use the Eclipse IDE’s refactoring feature – extract interface – to create a new interface from an existing class.

Why is this important for systematic reuse? Because, by isolating and realizing common behavior you reduce the need for multiple components and classes to re-implement the same functionality. If two classes need the same piece of data, or if they both connect with the same external system, why would you want to code them separately?

Like this post? Subscribe to RSS feed or get blog updates via email.

tweet this add to post to facebook

%d bloggers like this: