12.07.2015 Views

Chapter 6 VB/Access Programming

Chapter 6 VB/Access Programming

Chapter 6 VB/Access Programming

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Information Systems Developers HandbookVisual Basic is a development of the BASIC (Beginners All-Purpose SymbolicInstruction Code) programming language. In 1965 Kemeny and Kurtz developed asimplified version of FORTRAN which they called BASIC. It provided theirstudents with an easy-to-use interactive language, which was translated intomachine language and executed as soon as it was entered. It had the advantage ofgiving students immediate feedback if a statement error was typed. Since that timethe language has undergone many updates, including the structured programmingtechniques in versions such as ‘True BASIC’. Later developments are QuickBasicand Visual Basic.‘Visual’ refers to the Graphical User Interface (GUI) features of Visual Basic. Ithas a standard set of objects that are used to create the user interface by theselection, drag, and drop on to a form, which is effectively the program’s screen.These objects allow novice programmers to create useful applications by learning afew key commands. On the other hand, the language allows professionals todevelop powerful commercial programs.6.2 General StandardsMaintenance of any application consumes a very large portion of the overall costsof any business computer system. Indeed, it has been estimated to consume sixtypercent of the overall total cost of the system. Practices that will reduce these costsare to be encouraged.Standards are adopted to assist programmers to write code in a consistent formatthat can be understood by themselves at a later date and by other programmers whomay be maintaining their programs. Standards will, undoubtedly, change fromorganisation to organisation and from time to time.The aim of teaching students to comply with particular standards is not to suggestthey are the only, or indeed the best, standards available. Nor is it to set thesestandards in concrete for all time. Rather, it is to encourage the development ofprograms that are consistent, easy to read and easy to understand. In doing so, thestaff in the department hope you will gain an appreciation of the difference betweena section of code that uses oblique terminology and one that uses clear, consistent,and meaningful language. Examine the example code below to determine what thecode is attempting to achieve. Which example is the easiest to read andunderstand?Page 64


<strong>Chapter</strong> 6<strong>VB</strong>/<strong>Access</strong> <strong>Programming</strong>6.3.2 Variable NamesStandard No 2. Each variable name must clearly describe the data and its typestored within it. A variable name must consist of three sections.The first section indicates the scope of the variable and may be zero or one lowercase character. When the scope of the variable is local to a procedure, there is noprefix. For a global variable, the prefix ‘g’ is used, and where the scope is at themodule level, the prefix is ‘m’.Local single variablesngGradePointAverageGlobal string variablegstrStudentNameModule boolean variablemblnIsAPrimeNumberThe second section must be three lower case characters that indicate the variabletype. This naming standard is based upon (some would say a corruption of), part ofthe Hungarian Convention developed by Charles Simonyi. (He was Hungarian bybirth: thus the convention gained its name.) This convention used one or twocharacters to indicate variable type. However, in later times this has been expandedto three characters for greater clarity. The Department of Information Systems, forthe most part, uses the three character standard recommended by Visual Basic andMicrosoft and is shown below.Data TypeBooleanByteCurrencyDate(Time)DoubleErrorIntegerLongSingleStringUser-Defined TypeVariantArrayPrefixblnbytcurdatdblerrintlngsngstrudtvntarrThis standard has been applied to the variable names shown in the previousexample. In sngGradePointAverage, the ‘sng’ indicates that the data type issingle, in gstrStudentName the data type is string, and inmblnIsAPrimeNumber the data type is boolean.Page 67


Information Systems Developers HandbookThe third section is comprised of a descriptive, meaningful variable name thataccurately describes the data stored in it. It is unlikely to consist of less than fourcharacters (seven, including the prefix), or more than 35 characters. A variablename in <strong>VB</strong> may be up to 255 characters in length, allowing considerable scope todevelop meaningful variable names. Another guideline to remember is, whereverpossible, use one or more full words joined together, not one or more abbreviations.6.3.3 Variable StyleStandard No 3. Each word within a variable name must commence with an uppercase character, while all other characters are lower case.The final standard for variable names involves the use of upper and lower caseletters. The style involves each word using upper case for the first character of eachword and lower case for the other characters, eg. sngGradePointAverage.This style is becoming widely accepted within the computing industry.6.3.4 <strong>VB</strong> ObjectsStandard No 4. Each object name must begin with three characters, in lower case,indicating the object type followed by a meaningful object name with the firstcharacter of each word in upper case.The first three characters in the object name are used to indicate the type of object,defined below. This naming standard is also based upon the HungarianConvention.The first three characters must be followed by meaningful object names with thefirst character of each word in upper case, eg. cmdDisplayStudentStatus.Object typetext boxlabelcommand boxpicture boxlist boxPrefixtxtlblcmdpiclstPage 68


<strong>Chapter</strong> 6<strong>VB</strong>/<strong>Access</strong> <strong>Programming</strong>6.3.5 Procedure DeclarationStandard No 5. All parameter declarations must be explicitly declared. Forexample, always include ByVal or ByRef in the subprocedure or function parameterdeclarations.All procedures and their parameters must be explicitly declared. That is, the defaultstatus of SubPrograms and Functions and the form in which arguments are passedto them should not be relied upon. Therefore, all procedures must be explicitlydeclared Private or Public and all parameters must be declared ByVal or ByRef.Explicit procedure declarationPrivate Sub ValidateDate(ByRef datDueDate as Date)Rather thanSub ValidateDate(datDueDate as Date)6.3.6 One Expression Per LineStandard No 6. Limit your code to one expression per line.As Visual Basic uses interpreted or p-code executables (unless an executable file ismade), there is no speed advantage to placing more than one expression per line.However, there is a considerable readability advantage to writing one expressionper line. Improved readability improves the potential for more efficientmaintenance.One expression per lineIf intTotalMark >= 90 ThenGrade = “HD”End IfRather thanIf intTotalMark >= 90 Then Grade = “HD”6.3.7 Indent Within Loops and SelectionsStandard No 7. Indent within decisions (if statements) and repetition (loops).Indentation within if statements and loops allows easy identification of the code thatis within the specific if or loop. Indentation is particularly important for embeddedstructures, that is, embedded if statements, if statements within loops, or loopswithin loops. This indentation assists programmers when writing code, debugging,Page 69


Information Systems Developers Handbookor maintenance by clearly showing where each statement or loop starts and finishes.The programmer can easily identify common errors, such as failing to end a loop orplacing a line of code outside the if statement when it should be within it.Indent within If statements and LoopsFor intIndex = 1 to LengthOflstCustomerStatement 1...If lstCustomerNo(intIndex) = txtCustomerNo ThenStatement 1Statement 2...End IfStatement n...Next intIndexRather thanFor intIndex = 1 to LengthOflstCustomerStatement 1...If lstCustomerNo(intIndex) = txtCustomerNo ThenStatement 1Statement 2...End IfStatement n...Next intIndex6.4 Coding for ReusabilityCode can be reused in a number of ways. It can be reused within a program bydeveloping applications high in cohesion, that is, by writing code in subproceduresand functions. Ideally, each subprocedure or function will process only one task.Whenever that particular task needs to be processed that module can be called. Ofcourse, there are other considerations. A specific task may require different datavalues at different times. That data will need to be passed to the module at the timeof possessing. This, naturally, is passed from the calling procedure as an argumentand received by the called procedure’s parameter. It is in the passing and receivingof data that loose coupling is important. Coupling is the extent to which theinformation exchange between procedures is independent of other procedures. Thenext section will look at cohesion and coupling in greater depth.However, before doing so, there is another way code can be reused. That is, byimporting code that has already been written to do a particular task. This is easilyachieved in <strong>VB</strong> by including modules, forms, etc. Students will be reusing codeextensively, in the form of modules (*.bas). This will allow you to see how amodule that is developed and thoroughly tested, can be reused many times. Theprogrammer may take a ‘black box’ approach, as knowledge of the inner workingsPage 70


<strong>Chapter</strong> 6<strong>VB</strong>/<strong>Access</strong> <strong>Programming</strong>of a module is not required in order to use it. Indeed, we all do this every time abuilt-in function or one of <strong>VB</strong>’s standard objects is used. Each function or objectconsists of code that processes the task we ask and expect it to do. The fact that wedo not have access to that code does not affect our use of it.Back to <strong>VB</strong>’s modules. All you need to know about the module to use it effectivelyis:• the task the module performs;• the data and its type that is required by the module; and• the data, and its type, that is returned by the program.(In fact, this is the same information you need to use a subprocedure or function).It is surprising just how little code needs to be written to implement some verypowerful programs. All that is required to include a module is to let the programknow the address of that module. In <strong>VB</strong> this is achieved by choosing ‘Project’ onthe menu and adding the appropriate module or form to be included.It is important to note that it is the disk address that is stored in yourprogram. Therefore, if you move the site of the module you willhave to re-add the module (address) to your program or it will not beable to find the required module. <strong>VB</strong> will display an error messageas it is loading a program if it cannot find any added module or form.Continue to load the program, add the errant module, remember tosave the program and this should alleviate any further problems.6.5 Procedural <strong>Programming</strong>: Cohesion & CouplingIn traditional procedural applications, the application controls which sections ofcode are executed and in which order. When the application is run, the code isprocessed sequentially from the first line to the last line, calling sub procedures orfunctions as required. The user has no control over the sequence of the processingexcept via the choices the system requires them to make. The figure, ‘TraditionalProcedural Application’, shows the entry point of the application. It begins at thetop module and executes from there. Let us assume there is a menu in this module.The user may choose one of the menu options, which is executed. Uponcompletion, the system returns to the menu to allow the user to make anotherchoice. The user is not able to proceed directly from one menu option to anotherwithout returning to the menu.Page 71


Information Systems Developers HandbookProcedural programming techniques allow for the development of code with a highlevel of cohesion and loose coupling. A high level of cohesion means that eachsection of code (a subprogram or a function) processes only one task. This sectionof code may be called whenever that particular task is required, thus encouragingthe reuse of code.Traditional Procedural ApplicationMenuOption 1Option 2Option 3Loose coupling is achieved by using local variables and passing data betweensubprograms and functions whenever that data is required in another program,rather than declaring that data as global data. The drawback with global data is thatit is difficult to track the value of that data at any specific instance. Judicial use ofarguments passed between subprograms and functions allows for better tracking ofdata values. This is particularly so when data is passed by value from one sub toanother. These techniques also allow for the efficient reuse of code.6.6 Event Driven <strong>Programming</strong> TechniquesThe main feature of event driven programming is that the control does not follow apredetermined path. An event may be triggered by the system, other applications,or by the user actions. For example:• system timer• user actions command buttonmouse movekey stroke• application load formThe sequence of events determines the sequence of code execution. Typically thesequence of events changes each time the application is run. This allows for greaterflexibility in the utility of these applications and is a major contributor to thePage 72


<strong>Chapter</strong> 6<strong>VB</strong>/<strong>Access</strong> <strong>Programming</strong>increased ‘user-friendliness’ of modern applications. However, from aprogrammer’s viewpoint, it adds complexity to the design of the application. As thesequence of events cannot be predicted, the application must make assumptionsabout the ‘state of the world’ when it executes. The programmer must structure theapplication so that these assumptions are always valid. For example, if anassumption is made that the user will have made an input to an entry field, the codemust ensure that input has been made before the event can occur. In suchcircumstances, a check must be included to ensure the data has been entered beforeallowing the event to proceed.The application shown in the figure, ‘Event-driven Procedural Application’ consistsof identical processes to the application shown in the previous figure, ‘TraditionalProcedural Application’. However in the event-driven application there aremultiple possible entry points and the user may choose any of these entry points atrandom. Each of the entry points represents an event.Event-Driven Procedural ApplicationEvent 12Event 21Opt io n 1MenuEvent 3 Event 4Opt ion 2Opt io n 3Page 73


Information Systems Developers Handbook6.7 References and Suggested ReadingsMicrosoft Visual Basic Programmer’s Guide.Robertson, L.A. 1993, Simple Program Design, 2 ndThomas Nelson, South Melbourne.edn,Schneider, D.I. 1999, An Introduction to <strong>Programming</strong> UsingVisual Basic 6.0, 4 th edn,Prentice Hall, London.Page 74

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!