Monday, July 10, 2000

Programming Tips & Tricks #0006---Named Visual Basic Arguments

Tips & Tricks #0006

Named Visual Basic Arguments

One of the themes I emphasize in my computer classes over and over again is the importance of writing code that is readable---that is, code that other programmers and developers will be able to understand, and if necessary, easily modify in the future. Some obvious ways to write readable code include the use of program comments in your code---no matter what the language you are using to develop your program, all major languages provide for comments. Something else that can make your Visual Basic more readable is the user of Named Arguments.

Let me illustrate by executing the Visual Basic MsgBox Function to display a Windows Message Box. The Visual Basic MsgBox function has one required argument (Prompt), and four optional arguments (Buttons, Title, HelpFile and Context).

MsgBox “I love Visual Basic”

By default, this code will display a Message Box with a single command button captioned OK, with the text “I love Visual Basic”, and the Visual Basic Project name displayed in the Title Bar of the Message Box.

Suppose I’m not happy with the default Title in the Message Box, and I decide I want to customize it. Doing this is easy—all I need to do is supply the Title argument to the MsgBox function. However, since Title is the third argument, I either need to supply the second argument---Buttons, which is by default presumed to be the value vbOKOnly---or provide a ‘comma placeholder’, like this.

MsgBox “I love Visual Basic”,, “SearchVB.Com”

Notice the two commas back-to-back, with no value in-between. This is the ‘comma placeholder’ and is how we tell VB that although we have a value for the third argument, we have no explicit value for the second argument.

When we execute this code, we’ll see a Message Box that reads “I love Visual Basic”, and that has “SearchVB.Com” for its Title Bar.

Named Arguments can make passing optional arguments easier—and make your code infinitely easier to read and modify. For instance, the code we wrote above can be re-written to this using Named Arguments.

MsgBox Prompt:="I love Visual Basic", Title:="SearchVB.Com"

With Named Arguments, we specify the name of the argument, followed by a colon and equals sign (:=), then the value for the argument. By using Named Arguments, we don’t need to provide a ‘comma placeholder’ for the second argument Buttons. Since we are naming the argument, VB knows that ‘SearchVB.Com’ is the value for the Optional Argument ‘Title’. And since we name the arguments, being able to read and understand the code in the future is much easier.

No comments: