View
215
Download
3
Category
Preview:
Citation preview
Nguyen 1
Khoa Nguyen
Dr. Lyle
CSC 415 – Programming Languages
26 October 2011
Visual Basic
I. History of Visual Basic
Visual Basic 1.0 (May 1991) was released for Windows at the Comdex/Windows World
trade show in Atlanta, Georgia.
VB 1.0 for DOS was released in September 1992.
VB 2.0 was released in November 1992.
VB 3.0 was released in the summer of 1993 and came in Standard and Professional versions.
VB 4.0 (August 1995) was the first version that could create 32-bit as well as 16-
bit Windows programs. It has three editions; Standard, Professional, and Enterprise.
With version 5.0 (February 1997), Microsoft released VB exclusively for 32-bit versions of
Windows.
VB 6.0 (Mid 1998) improved in a number of areas including the ability to create web-based
applications. Mainstream Support for Microsoft Visual Basic 6.0 ended on March 31, 2005.
Extended support ended in March 2008.
Visual Basic .NET is Microsoft's designated successor to Visual Basic 6.0, and is part of
Microsoft's .NET platform. Visual Basic.Net compiles and runs using the .NET Framework.
It is not backwards compatible with VB6. An automated conversion tool exists, but fully
automated conversion for most projects is impossible.
("Visual Basic," 2011)
Nguyen 2
II. Overview of Visual Basic Design, Syntax, and Semantics
a. Names, Bindings, and Scopes
i. Names:
The most popular naming methods are CamelCasing, and UPPER_CASING. Camel
casing is that all words have the 1st letter in uppercase without any word separation, and the
subsequent letters in lowercase, while uppercasing is that all words are in upper case with an
underscore separator. (Karabatsos & Trescowthick, 2004)
When we name an element in our Visual Basic application, the first character of that
name must be an alphabetic character or an underscore. Note, however, that names beginning
with an underscore are not compliant with the Common Language Specification (CLS). The
following suggestions apply to naming.
Begin each separate word in a name with a capital letter, as
in FindLastRecord and RedrawMyForm.
Begin function and method names with a verb, as in InitNameArray or CloseDialog.
Begin class, structure, module, and property names with a noun, as
in EmployeeName or CarAccessory.
Begin interface names with the prefix "I", followed by a noun or a noun phrase,
like IComponent, or with an adjective describing the interface's behavior,
like IPersistable. Do not use the underscore, and use abbreviations sparingly, because
abbreviations can cause confusion.
Begin event handler names with a noun describing the type of event followed by the
"EventHandler" suffix, as in "MouseEventHandler".
Nguyen 3
In names of event argument classes, include the "EventArgs" suffix.
If an event has a concept of "before" or "after," use a suffix in present or past tense, as in
"ControlAdd" or "ControlAdded".
For long or frequently used terms, use abbreviations to keep name lengths reasonable, for
example, "HTML", instead of "Hypertext Markup Language". In general, variable names
greater than 32 characters are difficult to read on a monitor set to a low resolution. Also,
make sure our abbreviations are consistent throughout the entire application. Randomly
switching in a project between "HTML" and "Hypertext Markup Language" can lead to
confusion.
Avoid using names in an inner scope that are the same as names in an outer scope. Errors
can result if the wrong variable is accessed. If a conflict occurs between a variable and
the keyword of the same name, we must identify the keyword by preceding it with the
appropriate type library. For example, if we have a variable called Date, we can use the
intrinsic Date function only by calling DateTime.Date.
("Visual Basic Naming Conventions" 2011)
ii. Bindings:
There are two types of bindings: early and late bindings.
An object is bound early when it is assigned to a variable declared to be of a specific object type.
For example:
Dim MyVariable As StringMyVariable = "About Visual Basic"
is an early binding. We specified the variable as a string then assign value to it. In contrast, late
binding means that we do not explicitly specify the file type, the program will figure it out later.
An example would be:
Nguyen 4
Dim MyVariable As ObjectMyVariable = "About Visual Basic"
where we don’t specify a special type of the variable, the only way the program knows it is a
string is by finding where the assignment is within the code. Early binding has a few advantages
over late binding:
It makes the program run faster since code to convert to the actual type isn't
necessary.
The compiler can help find errors that might otherwise cause a runtime program
crash.
Intellisense code completion and Dynamic Help only works with early bound
variables.
Visual Basic supports both types of data binding. Nevertheless, we should use early binding due
to the above advantages over late binding.
(Mabbutt)
iii. Scopes:
In Visual Basic there are three scopes at which a variable may be defined. If defined
within a procedure, the variable is local to that procedure. If defined in the general declarations
area of a form or module then that variable can be referenced from all procedures in that form or
module and is said to have module scope. Finally, if it is defined with the “Public” keyword, then
it is global to the application. This means that the variable can be accessed throughout the
application without any restrictions. An example of different scopes implementation would be:
Module Module1
Public GlobalInteger As Integer Dim ModuleInteger As Integer Sub Main() Dim LocalInteger As Integer End Sub
Nguyen 5
End Module
(Karabatsos & Trescowthick, 2004)
b. Data Types: Visual Basic supports an abundance of data types:
Visual Basic type Structure Nominal storage
allocation
Value range
Boolean Boolean Depends on
platform
True or False
Byte Byte 1 byte 0 through 255 (unsigned)
Char Char 2 bytes 0 through 65535 (unsigned)
Date DateTime 8 bytes 0:00:00 (midnight) on January 1, 0001 through
11:59:59 PM on December 31, 9999
Decimal Decimal 16 bytes 0 through +/- 7.9...E+28 with no decimal point; 0
through +/-7.9228162514264337593543950335
with 28 places to the right of the decimal;
smallest nonzero number is +/-1E-28
Double (double-
precision floating-
point)
Double 8 bytes 1.79769313486231570E+308 through -
4.94065645841246544E-324 for negative values;
4.94065645841246544E-324 through
1.79769313486231570E+308 for positive values
Integer Int32 4 bytes -2,147,483,648 through 2,147,483,647 (signed)
Long (long
integer)
Int64 8 bytes -9,223,372,036,854,775,808 through
9,223,372,036,854,775,807 (9.2...E+18) (signed)
Object Object(clas 4 or 8 bytes Any type can be stored in a variable of
Nguyen 6
s) type Object
SByte SByte 1 byte -128 through 127 (signed)
Short (short
integer)
Int16 2 bytes -32,768 through 32,767 (signed)
Single (single-
precision floating-
point)
Single 4 bytes -3.4028235E+38 through -1.401298E-45 for
negative values;
1.401298E-45 through 3.4028235E+38 for
positive values
String (variable-
length)
String Depends on
platform
0 to approximately 2 billion Unicode characters
UInteger UInt32 4 bytes 0 through 4,294,967,295 (unsigned)
ULong UInt64 8 bytes 0 through 18,446,744,073,709,551,615
(1.8...E+19) (unsigned)
UShort UInt16 2 bytes 0 through 65,535 (unsigned)
User-Defined (str
ucture)
(inherits
from
valueType)
Depends on
platform
Each member of the structure has a range
determined by its data type and independent of
the ranges of the other members
("Data Type Summary (Visual Basic)" 2011)
c. Expressions and Assignment Statements:
Like other modern languages, assignment statements in Visual Basic carry out
assignment operations, which consist of taking the value on the right side of the assignment
operator (=) and storing it in the element on the left. It follows the structure: <variable name> =
<expression>
Nguyen 7
Dim r, s, t As Booleanr = Trues = 45 > 1003t = 45 > 1003 Or 45 > 17' The preceding statements assign False to s and True to t.
As we see in the above example, the right side of an assignment statement can be a single-valued
variable or can be an expression.
d. State-Level Control Structures
Control Structures in VB consist of three major groups:
i. Decision Structures: Describes control structures used for branching.
1. If…Then…Else
This construction lets us test for one or more conditions and run one or more statements
depending on each condition. We can test conditions and take actions in the following ways:
Run one or more statements if a condition is True
Run one or more statements if a condition is False
Run some statements if a condition is True and others if it is False
Test an additional condition if a prior condition is False
The control structure that offers all these possibilities is the If...Then...Else Statement
(Visual Basic). We can use a single-line version if we have just one test and one statement to run.
If we have a more complex set of conditions and actions, we can use the multiple-line version.
2. Select…Case:
This one lets us evaluate an expression one time and run different sets of statements
based on different possible values
3. Try…Catch…Finally:
Nguyen 8
This construction lets us run a set of statements under an environment that retains control
if any one of our statements causes an exception. We can take different actions for different
exceptions. We can optionally specify a block of code that runs before we exit the
whole Try...Catch...Finally construction, regardless of what occurs
Try Process.Start("http://www.microsoft.com")Catch ex As Exception MsgBox("Can't load Web page" & vbCrLf & ex.Message)End Try
ii. Loop Structures: Discusses control structures used to repeat processes
1. While Loops:
The While...End While construction runs a set of statements as long as the condition
specified in the While statement is True.
2. Do Loops:
The Do...Loop construction allows us to test a condition at either the beginning or the end
of a loop structure. We can also specify whether to repeat the loop while the condition
remains True or until it becomes True.
3. For Loops:
The For...Next construction performs the loop a set number of times. It uses a loop
control variable, also called a counter, to keep track of the repetitions. We specify the starting
and ending values for this counter, and we can optionally specify the amount by which it
increases from one repetition to the next.
4. For Each Loops:
Nguyen 9
The For Each...Next construction runs a set of statements once for each element in a
collection. We specify the loop control variable, but we do not have to determine starting or
ending values for it
For Each number As Integer In New Long() {45, 3, 987} Console.Write(number & " ") Next 'Output: 45 3 987
iii. Other Control Structures: Describes control structures used for resource
disposal and object access
1. Using…End Using:
The Using...End Using construction establishes a statement block within which we make
use of a resource such as a SQL connection. We can optionally acquire the resource with
the Using statement. When we exit the Using block, Visual Basic automatically disposes of the
resource so that it is available for other code to use. The resource must be local and disposable
2. With…End With:
The With...End With construction lets us specify an object reference once and then run a
series of statements that access its members. This can simplify our code and improve
performance because Visual Basic does not have to re-establish the reference for each statement
that accesses it. I find this structure very useful simple because some modern languages (i.e. C#)
don’t have this structure
With testObject .Height = 100 .Text = "Hello, World" .ForeColor = System.Drawing.Color.Green .Font = New System.Drawing.Font(.Font, System.Drawing.FontStyle.Bold)End With
("Control flow in visual basic" 2011)
Nguyen 10
e. Subprograms
In computer science, a subroutine (also called procedure, function, routine, method,
or subprogram) is a portion of code within a larger program that performs a specific task and is
relatively independent of the remaining code.
("Subroutine," 2011)
In VB, a Function procedure is used when we need to return a value to the calling code.
On the other hand, a Sub procedure is used when we do not need to return a value.
We can use Function only at module level. This means the declaration context for a function
must be a class, structure, module, or interface, and cannot be a source file, namespace,
procedure, or block. Function procedures default to public access. We can adjust their access
levels with the access modifiers. We can use a Function procedure on the right side of an
expression when we want to use the value returned by the function. We use
the Function procedure the same way we use any library function such as Sqrt, Cos, etc.
We call a Function procedure by using the procedure name, followed by the argument list in
parentheses, in an expression. This use is very similar to other modern languages like Java or C#.
Nevertheless, the next characteristic is a little bit different: we can omit the parentheses only if
we are not supplying any arguments. However, our code is more readable if we always include
the parentheses. A function can also be called using the Call statement, in which case the return
value is ignored.
(“Function Statement (Visual Basic)”, 2011)
f. Support for Object-Oriented Programming:
Nguyen 11
Visual Basic .NET is a fully object-oriented programming language, which means it supports the
four basic tenets of object-oriented programming: abstraction, encapsulation, inheritance, and
polymorphism (Hamilton)
i. Abstraction
In object-oriented software, complexity is managed by using abstraction. Abstraction is a
process that involves identifying the crucial behavior of an object and eliminating irrelevant and
tedious details (Hamilton). A good example of abstraction interpretation in Visual Basic is the
use of abstract classes.
An abstract class is a class that is not used for the purpose of creating objects. It acts as a
base class to be inherited by other classes. In other words, an abstract class provides a foundation
upon which other classes are built. In Visual Basic .NET we create an abstract class by using
the MustInherit keyword. An abstract class like all other classes can implement any number of
members. Members of an abstract class can either be Overridable (all the inheriting classes can
create their own implementation of the members) or they can have a fixed implementation that
will be common to all inheriting members ("OOP with VB" )
ii. Encapsulation
Object-oriented programming is based on encapsulation. When an object’s state and
behavior are kept together, they are encapsulated. That is, the data that represents the state of the
object and the methods (Functions and Subs) that manipulate that data are stored together as a
cohesive unit.
In Visual Basic .NET, the construct used to define an abstraction is called a class.
The terms class and object are often used interchangeably, but an object is actually an
instance of a class. A component is a collection of one or more object definitions, like
Nguyen 12
a class library in a DLL.
(Hamilton)
iii. Inheritance
A key feature of OOP is reusability. It's always time saving and useful if we can reuse
something that already exists rather than trying to create the same thing again and again. Using
Inheritance we can use the variables, methods, properties, etc, from the base class and add more
functionality to it in the derived class.
Public Class One------End Class
Public Class Two Inherits One---(more functionality here)---End Class
("OOP with VB")
iv. Polymorphism
Polymorphism provides the ability to vary the implementation of a method or property. With
polymorphism, the same method or property can perform different actions depending on the run-
time type of the instance that invokes it. Methods or properties that are polymorphic are
called overridable. By contrast, the implementation of a non-overridable method or property is
invariant; the implementation is the same whether the method or property is invoked on an
instance of the class in which it is declared or an instance of a derived class. When a non-
overridable method or property is invoked, the compile-time type of the instance is the
determining factor. In the following example, the class Shape defines the abstract notion of a
geometrical shape object that can paint itself:
Nguyen 13
MustInherit Public Class Shape Public MustOverride Sub Paint(ByVal g As Graphics, _ ByVal r As Rectangle)End Class
Public Class Ellipse Inherits Shape
Public Overrides Sub Paint(ByVal g As Graphics, ByVal r As Rectangle) g.drawEllipse(r) End Sub End Class
Public Class Box Inherits Shape
Public Overrides Sub Paint(ByVal g As Graphics, ByVal r As Rectangle) g.drawRect(r) End Sub End Class
The Paint method is MustOverride because there is no meaningful default implementation.
The Ellipse and Box classes are concrete Shape implementations. Because these classes are
not MustInherit, they are required to override the Paint method and provide an actual
implementation.
(“4.5 Polymorphism”, 2011)
i. Exception Handling and Event Handling
1. Exception Handling:
Visual Basic supports structured exception (error) handling, which allows the program to
detect and possibly recover from errors during execution. Visual Basic uses an enhanced version
of the Try...Catch...Finally syntax already supported by other languages such as C++. Structured
exception handling combines a modern control structure (similar to Select Case or While) with
exceptions, protected blocks of code, and filters.
Structured exception handling, which is the recommended method of error handling in
Visual Basic, makes it easy to create and maintain programs with robust, comprehensive error
Nguyen 14
handlers. Unstructured exception handling using On Error can degrade application performance
and result in code that is difficult to debug and maintain.
(“Exception and Error Handling in Visual Basic”, 2011)
2. Event Handling:
Visual Basic has a wide range of events and event handlers to be associated together. Any
subroutine can be an event handler except a function because it cannot return a value to an event
source.
Event handlers are procedures that are called when a corresponding event occurs. We can
use any valid subroutine with a matching signature as an event handler. We cannot use a function
as an event handler, however, because it cannot return a value to the event source.
Visual Basic uses a standard naming convention that combines the name of the event sender, an
underscore, and the name of the event. For example, the Click event of a button
named button1 would be named Sub button1_Click.
("Events and Event Handlers," 2011)
III. Evaluation of Visual Basic
a. Readability
In my opinion, Visual Basic is designed wonderfully for the purpose of readability. The
syntax and semantics are appealing to the eyes when we try to read the code. For instance:
Public Class Ellipse Inherits Shape
Public Overrides Sub Paint(ByVal g As Graphics, ByVal r As Rectangle) g.drawEllipse(r) End Sub End Class
Nguyen 15
We can see that VB uses “End Class” key words to end a class. For the same purpose,
other languages like C#, C++ and Java use the closing bracket ‘}’ which makes it a little harder
to read. We also notice that when the class Ellipse inherits from Shape, it literally says “Inherits
Shape” while other languages accomplish the same by using colon (“Public Class Ellipse:
Shape”). In addition, using a good IDE like Visual Studio can certainly boost readability because
of all the great color coding implemented within the product. In brief, VB is a very readable
programming language for its syntax is fairly close to English and becomes even better with the
use of Visual Studio.
b. Writability
Aside from readability, we will have to talk about writability. Using the above example,
we can see that it takes extra time to write “End Class” or “End Sub” or things of that nature.
While in other languages, we can use closing brackets which is much faster from the writability
stand point. So there we have it, a language that does an excellent job in readability, does not do
a very good job in writability. It is a fair trade off.
However, on the compiler’s stand point, since VB.NET is contained within the .NET family and
supported by a strong IDE called Visual Studio, things are made fairly easier when it is time to
code. With VS, developers can drag and drop controls into forms, double click on a control to
write an event handler, set properties of controls from the properties window, etc. All of those
used to be done by plain old hand coding. Nowadays, we can perform tasks like those and Visual
Studio will generate the code needed for those actions to be done in a split second. That certainly
helps in saving coding time for developers and increasing productivity on mission-critical
projects.
Nguyen 16
In short, although VB’s writability suffers from the greatness of readability, the Visual Studio
adds a huge boost to writability in the event that developers are able to afford a big IDE like that.
c. Reliability
Is Visual Basic reliable? The question resides less on the language but more on the
compiler itself. So we will have to ask ourselves: “Is Visual Studio reliable?” To dig deeper on
that, the compiler uses .NET framework created by Microsoft, running on Windows operation
system. Therefore, the question can be extended to whether the framework plus the OS are
reliable or not. Different people will have various ideas about this question, but in my opinion, I
think it is fairly reliable except for a few rare occasions. The way I see it, if Windows is not
reliable, it would not be used widely in our machines these days. Moreover, based on my
experience, I have not seen many inconsistencies within the applications that I’ve written or have
helped develop using the .NET framework. Almost all the problems are caused by bugs due to
programming flaws not because of the language itself. In short, Visual Basic, which is supported
under .NET framework, is fairly reliable to the best of my knowledge.
d. Cost
The easiest and priciest way to do Visual Basic is to go with Visual Studio. Visual Studio
2010 Ultimate costs roughly $10,000 with MSDN (new subscription). The premium version
sounds a little bit better with the cost of $5500 with MSDN (new subscription). The professional
one costs less with $1200 with MSDN (new subscription) or $800 only with MSDN essentials. If
we add the cost of training somebody to learn Visual Basic then it will depend on that person’s
knowledge and skills. If he is an experienced programmer, giving a few weeks of researching
and he will be good to go. On the flip side, it can take months for him to pick it up and we know
the training cost is proportional with the time it takes to train that particular employee.
Nguyen 17
IV. Bibliography and References
4.5 Polymorphism. (2011). Retrieved from
http://msdn.microsoft.com/en-us/library/aa711874(v=vs.71).aspx
Control flow in visual basic. (2011). Retrieved from
http://msdn.microsoft.com/en-us/library/ca8tdhcs(v=VS.100).aspx
Data Type Summary (Visual Basic). (2011). Retrieved from
http://msdn.microsoft.com/en-us/library/47zceaw7(v=VS.100).aspx
Events and Event Handlers. (2011). Retrieved from
http://msdn.microsoft.com/en-us/library/2z7x8ys3(v=VS.90).aspx
Exception and Error Handling in Visual Basic. (2011). Retrieved from
http://msdn.microsoft.com/en-us/library/s6da8809(v=VS.100).aspx
Function Statement (Visual Basic). (2011). Retrieved from
http://msdn.microsoft.com/en-us/library/sect4ck6.aspx
Hamilton, J. P. Object-oriented programming with Visual Basic .NET. (p. 3). Retrieved from
http://oreilly.com/catalog/objectvbnet/chapter/ch01.pdf
Karabatsos , J., & Trescowthick, M. (2004). Visual Basic/Coding Standards. Wikibooks. GUI
Computing Pty Ltd. Retrieved from
http://en.wikibooks.org/wiki/Visual_Basic/Coding_Standards
Kimmel, P. (2002, March 08). Working with new abstract data types in visual basic net.
Retrieved from http://www.informit.com/articles/article.aspx?p=25868
Mabbutt, D. (n.d.). Early binding and late binding. Retrieved from
http://visualbasic.about.com/od/usingvbnet/a/earlybind.htm
Nguyen 18
Oop with vb . (n.d.). Retrieved from http://www.startvbdotnet.com/oop/abstract.aspx
Subroutine (2011). Wikipedia. Retrieved from http://en.wikipedia.org/wiki/Subroutine
Visual Basic (2011). Wikipedia. Retrieved from http://en.wikipedia.org/wiki/Visual_Basic
Visual Basic Naming Conventions. (2011). Retrieved from
http://msdn.microsoft.com/en-us/library/0b283bse(v=VS.100).aspx
Recommended