Promoting Code Reuse Often in programming, multiple procedures will perform the same operation IN...

Post on 22-Dec-2015

214 views 2 download

Tags:

Transcript of Promoting Code Reuse Often in programming, multiple procedures will perform the same operation IN...

Promoting Code Reuse

Often in programming, multiple procedures will perform the same operation

IN OTHER WORDS – the same piece of code will do the same thing somewhere else in the application

Rather than retyping the code twice (or even more than twice….), code can be written in a general

(sub/function) procedure and can be called into use from other procedures (therefore promoting

reuse)

Promoting Code ReuseClick each command button triggering the click event procedure associated with each one

Promoting Code Reuse

Now when we click on the hello command button we trigger the click event procedure associated with that command button but also call the other procedures which execute in turn producing the same output

Creating a ‘Sub Procedure’

The coding of a new procedure is similar to the other event procedures that we have been coding,

but is not in itself attached to any event

Therefore, this code cannot be executed unless a CALL is specified from another procedure, for the

General Sub Procedure

To call a Sub Procedure, just give the procedure name

Creating a ‘Sub Procedure’

• 2 ways to create a General Sub Procedure

• [1] simply type in the procedure definition in the code window

• [2] use the tools / add procedure menu command

Type sub myprocedure and press return on the keyboard and the procedure is created

Very Important - visibility• Sub procedures are by default Public in all

modules, which means they can be called from anywhere in the application

• So what is the scope of this newly created procedure?

Very Important - visibility

So you should put the PRIVATE keyword in front of the sub keyword to reduce the procedures visibility

tools / add procedure menu command

Creating a ‘Sub Procedure’

The Sub statement declares the name, arguments, and code that will form the body of a subroutine / sub procedure as follows:

[Private | Public] Sub ProcedureName [(arguments)]

statements

End Sub

Advantages of a ‘Sub Procedure’

Code is easier to write and debug - test individual modules

Code is maintainable

Improves code structure

Decreases the size of individual procedures and often the size of the program itself

Disadvantages of a ‘Sub Procedure’

Requires extra preparatory work

Need to understand logical design of code structure

May require more CPU time and memory

Calling a ‘Sub Procedure’

The use of the keyword Call is optional but required in certain cases:

ProcedureName

Call ProcedureName

Call ProcedureName ( )

An Event Procedure can also be called

Command1_Click

Call Command1_Click

Call Command1_Click ( )

Scope of Variables: General Sub Procedures

Example 1

Example 1Scope of Variables:

General Sub Procedures