Visual Basic .NET/Reusable Code

Previously we have learned about declaring variables and writing logical code. This lesson will focus on making reusable code through the use of functions, modules and subprocedures.

Introduction
Imagine that you have a fully fledged GUI interface for your program. A treeview control, several text boxes, some buttons, a few menus, and other odds and ends. Your program takes values entered into the text boxes and adds them to the treeview control. But you don't want just any values, you want MAC addresses. MAC addresses consist of 6 pairs of 2 digit hexidecimal characters. You want to validate the txt put in the control. Also, you want to add the value to the treeview control, but only if it is not already there.

The wrong way and the right way
One might be tempted to write code that produces the desired result for an action that you know several code blocks will need to perform. This works and is not hard to do, but it wastes a lot of space and makes your code harder to read, and harder to fix.

The above code helps illustrate. Both procedures execute exactly the same with only slight variations. Why not consolidate that code so that if future code additions need it, they can call it too? Below is how one might do this. Ahh, but what if I wanted to have the type of control change between code block? Easy, Just specify the type of control as another argument.

Functions
I know I went over functions previously, but it is worth noting that functions are specifically designed to be re-usable code. Take some value or reference (or not) do something and return a value. They are really not designed to do anything else. You can obviously affect objects with a function like changing colors in a control or something, but a function has to return a value (along all code paths I might add). There is no similar stipulation for Subroutines.

Exercise
Try designing a form with two buttons and two textboxes. Write some code that has one button multiplying the value in one textbox by 2 and outputting to the second textbox, and the other button multiplying by four and outputting the same way. An example of the finished code can be found on the talk page.