Tip #1 - Create Reusable blocks of code as Subroutines
Inline Code Blocks vs. Subroutines
It is easy to write a simple script as a straightforward series of procedural statements.
Such as simple script is written as a straightforward flow of discrete statements.
This is fine for really small programs, but as your program grows it becomes cumbersome. It becomes more and more difficult to read and follow the logic.
This can be partially eased by breaking the code into discrete logic blocks separated by blocks of comments. Still, as your program becomes more complex you find it becomes more difficult to analyze and troubleshoot. Ten lines of simple program steps is easy to grasp, but a thousand lines in the same format becomes difficult to work with.
You also often find yourself rewriting similar logic multiple times as you try to accomplish similar things in subtly different ways. You find yourself inventing the same wheel many times within your program.
If you instead try to think of the program as blocks of functionality and then code those blocks as callable subroutines, you can name them appropriately, call them from anywhere, and in general make more efficient use of your programming time.
Subroutines give you a convenient way to write code as simple blocks that can be easily reused.
Your subroutines can also be conveniently collected into a personal library of functions and reused as needed in many different programs.
Anatomy of a Subroutine
Subroutines have three major parts.
(1) Header. The Header consists of the word "sub" followed by a unique name. The name is followed by an open curley bracket '{' and the subroutine is ended with a closing bracket.
(2) Variables. Variables come in three styles. Global variables are common to the whole program and may be modified anywhere within the program.
Local variables are used strictly within the subroutine and any "child" subroutines called by the subroutine. Both forms of variables may be used to share data between the subroutine and other processes.
The ultimate in local variables are private variables designated via the keyword 'My' which are unique and private to the subroutine only.
(3) Parameters. Processing information within the bounds of a subroutine is of little value unless you can get your data in and out of it. There are several ways to do this.
The simplest way to do so is to simply use global variables for the data, and allow the subroutine to directly operate on the global. Simple, but prone to error. Nonetheless
there is definitely a time and place to use this technique.
Parameters may also be passed into a subroutine as arguments of the call. This is preferred. Results may be returned similarly.
|