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 use 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 the following way 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.
Written by John Smiley, MCP, MCSD and MCT, author, and adjunct professor of Computer Science at Penn State University in Abington, Philadelphia University, and Holy Family College. John has been teaching computer programming for nearly 20 years.
John Smiley is president of Smiley and Associates, http://www.johnsmiley.com/smass/smass.htm a computer consulting firm located in New Jersey.