Wednesday, June 2, 2010

Coding Standard

In this tutorial series, we will cover the proper or recommended ways of coding.  Although this tutorial is specific to Visual Basic 6.0, you can implement the idea in any language you use.

Note that all instances of the word Visual Basic refers to the classic, not VB.Net.


Visual Basic allows programmers to create applications in the shortest possible time.  That’s why it is considered or classified as RAD tool where RAD stands for Rapid Application Development.

One of the reasons VB can accomplish that much in a short span of time is that it is not “strict” in terms of declarations and code structures.  This means you can use a variable without declaring it first.  You don’t need explicit statement termination like semicolon (;), no need for open and close curly braces “{“, “}” to begin and end a code block and no indentation rule to follow as well.

Some of the best-known “strict” languages are C++ and Java, which enforces one or more of the coding rules.

But it doesn’t mean we cannot or should not exercise good coding practices when writing VB applications.

 

So when do we apply coding standard and when can we disregard it?

Here are some instances when to and when not to consider coding standard:


Use coding standard when:

Writing big applications like corporate applications

Writing applications with other developers

Writing anything that will be distributed or released and maintained

 

No need to use coding standard when:

Writing prototypes or proof-of-concept application

Testing a business rule or logic

Testing a technique or library or component


Of course all of the standards in the world will be useless if one forgets to implement them.  And one of the most neglected aspects in VB programming is variable declaration.  Sure VB doesn’t mind and like we discussed earlier that it is allowed to use a variable even without declaring it first.

When writing prototypes this is fine.  But when you have to debug thousand lines of codes, this would be a huge problem.

 

The easiest way to make sure you declare all variables before using them is by putting “Option Explicit” at the first line of ALL modules (form, basic, class).  See screenshot below:



Or you can let VB do it for you automatically by going to "Tools -> Options" and checking "require variable declaration" as seen below:




Now let's go to the actual coding standard.  


MODULE PREFIXES

VB has three (3) modules --- Form (*.FRM), Basic (*.BAS) and Class (*.CLS) and we can start from there.

Prefix form modules with "F" (yes, we will also use "frm" later).  So if you have the login form, you can name it "FLogin".

Prefix basic modules with "M" like "MCommon"

Prefix class modules with "C" like "CStudent" (yes, "cls" will also be used later)


CONTROL PREFIXES

Here are some prefixes for the most common controls:


CONTROL PREFIX EXAMPLE

Textbox txt txtUserName

Label lbl lblDescription

ComboBox cbo cboCountries

CommandButton cmd cmdCancel

ListBox lst lstDepartments

Frame fra fraBranches


Note that prefixes are small cased and the actual variable name is camel-cased or at least the first letter is capitalized.

The naming prefix can also be applied to other components like "lvw" for ListView, etc.

Just remember the prefix should indicate what type of control it is.  It might not look that helpful but again, when dealing with thousand lines of code, this prefix convention will mean a lot between beating the deadline or beating yourself to frustration.


PREFIXES BASED ON DATA TYPE


For variables here are some suggestions:


VARIABLE WHAT IT MEANS

intAge Integer data type variable for Age 

strEmpID String data type variable for Employee ID

sngSalary Single data type variable for Salary

blnSuspended Boolean data type variable for Suspended


Now if you want to reference a form or class in your code, now is the time to use "frm" and "cls" as in the example below:


dim frmPrompt as FUserPrompt

dim clsEarth as CPlanet

(See?  I told you we will use "frm" and "cls")


For constants, you simply add "c" in the front.  Here is an example:

CONST csngPi as Single = 3.1416


Based on this, you can come up with the prefix for other data types.  Think of the prefix for data type Double and Object.


ADDITIONAL PREFIX BASED ON SCOPE

Although it's already a big help using prefix on the variables, we also need to know quickly the scope of the varialbe (or constant).

VB and some other languages have three scopes : local, modular and global (or public).


Local variables are those declared under a method (sub, function) and properties.

These variables don't need any additional prefix, see example below:


Private Sub Form_Load()

Dim strParams as String


End Sub


Modular variables are those declared at the modular level (available anywhere within the module).   We can prefix any modular variable with small "m".


See example below:


Option Explicit

Private mintLevel as Integer

Private Sub Form_Load()

mintLevel = 45

End Sub


Global or Public variables are those declared in any module using "Global" or "Public".  Both are supported by VB and they practically are the same in functionality.

Prefix Global variables with small "g" and for Public variables use "p" (see below)


In MCommon.BAS:

Global gstrSessionID as string


In FMain.FRM:

Private Sub Form_Load()

MsgBox gstrSessionID

End Sub


INDENTATION AND SPACING

Equally important is "how" we lay out the codes.  Computers and compilers will have no trouble reading your codes, but how about other programmers?  Or you 2 years from now?   How you write the code will be the key to easy maintenance and code debugging later on so if you don't want debugging to be a nightmare, make sure you code correctly.


Here is a sample of a VB code:


Private Sub Form_Load()

Dim r As Integer

Dim x As Integer

    For x = 1 To 5

r = gr(x, 2)

Debug.Print r

        Next

    MsgBox "done"

End Sub


Private Function gr(a, b)

gr = a * b

End Function




And here is the same code, with prefix, casing,  properly indented and spaced:


Private Sub Form_Load()

    Dim intResult           As Integer

    Dim intLoop             As Integer

    

    For intLoop = 1 To 5

        intResult = GetResult(intLoop, 2)

        Debug.Print intLoop & " x 2 = " & intResult

    Next

    

    MsgBox "Done"

End Sub


Private Function GetResult( _

ByVal intNum1 As Integer, _

ByVal intNum2 As Integer) As Integer

    

    GetResult = intNum1 * intNum2


End Function


Now which code would you like to maintain and work on?  


COMMENTS (but not too much)

We can still do more to make reading the codes easier to understand.  And also another neglegted part in programming is putting sufficient comments.


Private Function ComputeAverage( _

ByVal sngPrelim As Single, _

ByVal sngMidterm As Single, _

ByVal sngFinal As Single) As Single

    '

    ' this function computes the average grade

    ' using prelim, midterm, and final grades

    ' as input

    '

    On Error GoTo ErrorHandler

        

    Dim sngSum          As Single

    Dim sngAverage      As Single

        

    ' compute the sum of the grades first

    sngSum = sngPrelim + sngMidterm + sngFinal

    

    ' divide by three to get the average

    sngAverage = sngSum / 3

    

    ' return the result to caller

    ComputeAverage = sngAverage

    Exit Function

ErrorHandler:

    ' display error message to caller

    MsgBox Err.Description, vbExclamation, "Error on ComputeAverage"

End Function



MODULARIZE OR FOLLOW OOP

Another good practice is to divide the codes into logical groups.   Instead of writing everything in (for example) Form_Load, you can put certain business rules into methods (subs and functions) then call them from the main method.

So instead of writing the codes of "ComputeAverage" (exable above) inside Form_Load, we can just call it from there like this:


Private Sub Form_Load()

    sngAve = ComputeAverage(sngPG, sngMG, sngFG)

End Sub


This approach also provides reusability of codes, meaning you can call the ComputeAverage function in other methods or even in other modules (if global or public).
Extending this idea further is when you use libraries like ActiveX DLL/EXE and OCX.

Another benefit of modularizing codes is that it's easier to make the necessary changes and ensuring that all affected areas are updated properly.  If you "copy + paste" every code logic then when you need to change a part of it, you'll need to make changes to all codes you pasted them.  But by using this approach, the changes made on this would be effective to all calls made to it.

And for OOP (Object-oriented Programming), it doesn't necessarily mean you need to write DLLs or OCXs to implement its principles.  There are three (3) basic rules or principles of OOP and they are: Encapsulation, Inheritance and Polymorphism.  Related to our topic is the first one.

Encapsulation
Data of an object should be private.  External consumers (those that use the object) should have a method or property to affect it's value.  In short, avoid global variables.


Example:

Instead of declaring a global variable called "balance",

Global gsngBalance as Single


We should create a modular variable and a public method to update it:

Private msngBalance as Single

Public Sub Deposit(byval sngAmount as single)
msngBalance = msngBalance + sngAmount
End Sub


The intent is obvious.  You don't want anyone or any application to change the value of balance without the proper business rules.

Trust me, dealing with an application that has tons of global variables is frustrating and makes your coding life miserable.


For beginners this looks like a waste of time or extra work but for those of us who have been there, done that, this is worth the while.  There are more ways to write applications but this covers most of the basic concepts that a good programmer needs to know and apply.

Thanks for reading and happy coding to us all!


Friday, January 22, 2010

Say hello to VB6

If you already have Visual Basic 6.0 (or the portable one) then let's get it on!!!

When you run VB 6.0, you'll be presented with a screen containing the available projects you can make, like this one:



For now, we'll just be concerned and working on the "Standard EXE" project (default selection). So just click on "Open" button to start our first project.

Now you'll get to Visual Basics IDE (or Integrated Development Environment)
Although it contains a lot of icons and menus, we'll just worry about some of them.

The menu bar is on top and has the text-based "pull-down" menu and the icon-based menu (most of the items in the text-based and icon-based are identical. For example, the diskette icon is used for saving the project, and you can also save from the "File" pull-down menu.



The Toolbar is where you get the controls from. These controls can be placed on the form (see the center image with "Form1"?). You can click on a control from this toolbox, then "draw" it on the form. You can try it now if you want :)

Another important location of the IDE is the Project window. This is where the project modules are located. VB 6.0 has three major modules : form module, basic module and class module.
We're just gonna work on the form module for now.

The form and the controls (from the toolbox) have properties as most objects do. A student for example has the "student id" property. A student could also have a "course" property, etc.
The "Form1" on the top is the "Caption" property of the form (default highlighted).
If you change the value to "My Form" or anything you want, then you'll see that it will change.

The immediate window is a debugger window but we won't be discussing it this early.

Next, let's take a look at the project window (top-right). You have two basic views: the "code" view and the "object" view. As the name implies, "code" view enables you to view the code of the module (in this case the form module). The "object" view is the view of the form and all the controls in it.



The toolbox is almost always used since this is where you get the form decorations.


The most commonly used controls are:

- Label
- Textbox
- Command button

and later we'll be using these controls:

- Directory (or dir)
- Drive
- File
- Image

For now, you can select any control and just place it on the form just to get you familiar with putting controls on the form. Try also to "align" or place them nicely so that your form layout looks good enough.


Next we'll take a close look at the Properties window.

It is a "visual" representation of the properties of the controls and forms. I said "visual" because you may also access these properties from inside the code.

There are basically four parts of it that you'll be using:

The object name is what is currently selected. In this case the form object. When you click on a control in the form, this value changes (ex. Textbox1, Label1)

The property name is (of course) the name of the objects property. Like we said, a form has "Caption" property, "Height", "Width", etc.
The value is also there for you to edit. Then the description is shown below, a summary of what the property does or what it's for.

Okay, go back to "Object view" to see the form. Then double-click on the form (the large gray area of it). You should be taken to the "code" view.
Alternatively you can also go this via the "code" view button (as discussed in the Project window)

See below for the basic parts of the code view:



The object list contains the form and other objects that you have on a particular module. The method and property list changes depending on what object is selected.

The block of code is where you type the commands you want to happen when a property or "event" takes place.

Now, you're ready to code. Inside the code block "Form_Load()" type 'MsgBox "Hello world" then click on the "run" button. See image below:



You should now see the output of your first program:



When you click on "OK", the form (Form1) will be displayed.

Well, that's it. This is your first Visual Basic application. This is not that great, nor does it do anything fancy but it's a program nonetheless.

You may go back and review, try to re-do what we have done (without looking at this) and make sure you are familiar with the IDE, where the controls are located, how to change a property value, how to enter and change code and run the program.

The next post will present another application so be sure you practice well :)

Thanks for viewing, happy coding for now!

Sunday, January 17, 2010

Welcome to tutorials!!!

This is my blog to teach programming using Visual Basic 6.0. My target audience are beginners and old school programmers and this is also the language I'm most familiar with.
If you already are programming then most of the lessons will be obvious and familiar to you so you can probably skip them or just read on to see if there are some ideas I introduced that might be of use to you.
I would assume from the start that the reader has no programming experience but at least is familiar with computer operations like web browsing, sending/receiving emails, probably even used office suites like Ms Office and/or OpenOffice.

If you don't have a Visual Basic editor, you can try the link below:

http://www.plunder.com/VB6-portable-download-Visual-Basic-6-Portable-download-91935.htm

I don't own it, I just saw it while googling and wanted to share with you.

This will be useful so you can do the sample codes I will be posting and to try out what you have learned.