Microsoft Office 2000/Visual Basic Programmer's Guide   

What Is Reusable Code?

Reusable code is code that can be used, without modification, to perform a specific "service" regardless of what application uses the code.

There are everyday objects that perform a specific service in different circumstances all around you. Think of a calendar. It gives you the ability to look up days and dates. You can use it to determine that this year your birthday falls on a Tuesday, or that Thanksgiving is on the 25th, or that there are two extra days to file tax returns because April 15th is on a Saturday. Similarly, you can use your address book to create a Christmas card mailing list or find the phone number for your Aunt Sally. When you are building software, "objects" are created in code, and reusable objects that perform specific services in different circumstances are called components.

When you use Microsoft Office to build custom solutions, you write code that leverages the power of Office components. Using an Office component means that you not only don't have to write the code yourself, but you are using a component that has been tested and found reliable in different conditions. The day has long passed when any knowledgeable developer would consider writing a custom program to check spelling. Instead, you'd call the spelling checker provided with Word. Similarly, nobody would develop custom code to calculate depreciation or determine principal and interest payments on a long-term loan. Instead, you would call VBA's built-in financial functions or use the Excel Application object to handle complex calculations for you.

Just as you can build custom solutions based on components supplied as part of Microsoft Office, you can also build them by using reusable components that you have created yourself. You can think of reusable code from the perspective of the code that will call it to perform its service. It is a "black box" that accepts a known input value and returns a known output value. What happens inside the box (how the procedure actually works) is irrelevant to the code that calls it.

Once you get into the habit of writing reusable procedures, you will often find that you have solutions where groups of related procedures work together to perform a single service or a group of related services. For example, you may have a group of procedures that provides data access services, or another group that consists of string-handling routines. This is an opportunity to group related procedures in their own module (or in a class module that exposes methods and properties to gain access to the procedures). You can then add the module to any solution that needs the services it provides.