How to: Break Large Pieces of Code into Smaller Pieces

All executable statements in Visual Basic must be inside some procedure, such as Main, Form1_Load, or calculateTotal. It is possible to write your entire application as a single large procedure, but if you divide it into smaller ones, your code is more readable.

Structured programming is an approach that emphasizes program modularity and a hierarchical structure within an application. In Visual Basic, the most straightforward way to achieve structured programming is through judicious use of procedures to break your application into discrete logical units. You can debug each individual unit more easily than the entire program. You can also use a procedure developed for one program in other programs, often with little or no modification.

Breaking Up a Large Procedure

To break a large procedure into self-contained pieces

  1. Identify one or more self-contained sections of your code.

  2. For each self-contained section, move the source code outside the large procedure and surround it with the Sub and End Sub statements.

  3. At the place in your large procedure from which you removed the code section, add a statement that calls the Sub procedure.

Returning a Value to the Large Procedure

If it is useful for the new procedure to return a value to the large procedure, you can define a Function procedure.

To break out a section that returns a value

  1. Surround the removed source code with Function and End Function statements instead of Sub and End Sub.

  2. At the place where the Function procedure has the value ready to return to the calling code, add a Return statement.

  3. At the place in your large procedure from which you removed the code section, make sure the calling statement does something with the returned value. You can store it in a variable or use it in an expression.

See Also

Tasks

How to: Create a Procedure

Concepts

Procedures in Visual Basic

Sub Procedures

Function Procedures

Property Procedures

Operator Procedures

Procedure Parameters and Arguments

Recursive Procedures

Procedure Overloading

Other Resources

Object-Oriented Programming in Visual Basic