By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,230 Members | 1,358 Online
Bytes IT Community
Submit an Article
Got Smarts?
Share your bits of IT knowledge by writing an article on Bytes.

A 6-Pack of Good Programming Style Hints

ADezii
Expert 5K+
P: 8,669
  1. Indent - A procedure normally has several sections. There may be a section for error-handling code, groups of code lines for repetitive operations, alternative groups of statements to be executed under some conditions but not under others, etc. Indenting is a useful way to identify code sections. Although it makes absolutely no difference to the compiler, it does make your code easier to read and understand.

    Expand|Select|Wrap|Line Numbers
    1. Do
    2.   movespot = movespot / 2
    3.   MyRS.Move (movespot)
    4.     If StrComp(MyRS![LastName], searchadv) < 1 Then
    5.     ElseIf StrComp(MyRS![LastName], searchadv) = 0 Then
    6.       MsgBox "Exact Match"
    7.     Else
    8.       MyRS.Move (0 - movespot)
    9.         If Not MyRS.EOF Or MyRS.BOF Then
    10.           MyRS.MoveFirst
    11.         End If
    12.     End If
    13. Loop Until movespot < 2
  2. Use Comments - As you are creating code, the purpose and logic of a procedure's statements may seem obvious. Days or weeks later, the logic may be elusive to you and downright confusing to someone else. Save yourself and others time and effort by commenting your code. Comments should be included at the beginning of a procedure to describe the procedure's purpose, the arguments, and the value returned if a function procedure. It is not necessary to comment every line of code, in fact it is down right excessive, but you should at least include a comment to explain the logic of each group of statements. To designate a comment line, procede it with an apostrophe. By default, the VB Editor will change comment lines to green.
    Expand|Select|Wrap|Line Numbers
    1. 'Make sure to 1st set a Reference to the Microsoft Excel XX.X Object Library
    2. Dim objExcel As Excel.Application
    3. Set objExcel = CreateObject("Excel.Application")
  3. Use Naming Conventions - It is very important to establish a consistent pattern for naming objects you create in your applications. With a properly chosen, consistently applied naming convention for procedures, objects, constants, and variables, your VBA code becomes more self-documenting and easier to understand.
    Expand|Select|Wrap|Line Numbers
    1. Dim strLastName As String
    2. Dim lngZipCode As Long
    3. Dim blnFoundFile As Boolean
    4. Dim dteBirthDate As Date
    5. Dim rstNew As Recordset
    6. Dim dbNorthwind As Database
    7. Dim dblPie As Double
    8. Dim astrEmployees(100)     'an Array of Strings
    9. fExtractMiddleInitial(strFullName As String) As String   'Function
  4. Use Separate Lines For Each Statement - Although you can string together several statements separated by colons on a single line, avoid the urge to do so. The advantage of condensing your code is more than offset by the increased difficulty in reading it.
    Expand|Select|Wrap|Line Numbers
    1. Do While Not MyRS.EOF
    2.     'Avoid 2 statements on a single line
    3.     Debug.Print MyRS![LastName]: MyRS.MoveNext
    4. Loop
  5. Use the Line-Continuation Character - As you have probably noticed, the Module Window does not have a word-wrapping feature. If you enter a very long statement, you can wrap the statement yourself by use of the line-continuation character wich consists of a space followed by an underscore ( _). If you don't break a long line with this character, you will need to use the horizontal scrollbars to view parts of the statement. You can't use the line-continuation character to wrap a string expression to another line; instead, you can divide the string into smaller pieces and concatenate the pieces.
    Expand|Select|Wrap|Line Numbers
    1. Dim strMsg As String
    2. 'Instead of this
    3. 'strMsg = "The rules of Referential Integrity have been violated. You have made an attempt to enter a Training Record for an Employee in the Training Table when this individual doesn't exist in the Parent (Employees) Table. Enter a valid Employee Record first, then proceed"
    4.  
    5. 'Use this syntax
    6. strMsg = "The rules of Referential Integrity have been violated. You have made an " & _
    7.          "attempt to enter a Training Record for an Employee in the Training Table " & _
    8.          "when this individual doesn't exist in the Parent (Employees) Table. Enter " & _
    9.          "a valid Employee Record first, then proceed"
    10.  
    11. MsgBox strMsg, vbExclamation, "Referential Integrity Violation"
  6. Declare Variables and Constants at the Beginning of a Procedure - By grouping all declaration statements at the beginning of a procedure, you can see the constants and variables at a glance and avoid needing to hunt through procedure code to find them.
    Expand|Select|Wrap|Line Numbers
    1. Private Sub_SomeButton_Click()
    2. Dim dbMyDB As Database, rstMyRS As Recordset, intNoOfRecords As Long
    3. Dim intCounter As Integer, tdfNew As DAO.TableDef, fldOld As DAO.Field
    4. End Sub
May 6 '07 #1
Share this Article
Share on Google+
16 Comments


P: 1
I generally use Javascript as my scripting language along with ASP.

I have noticed that VBscript developers tend to initialize a group of constant global variables a the beginning of a script even though the script may only use that variable once. Since each variable takes up precious memory resources and the constant variable is already a literal string anyway; wouldn't it be better to use the literal strings hard coded into the script or application if only being used once or not at all in some cases, to free up memory resouces in an application.
Jan 9 '08 #2

ADezii
Expert 5K+
P: 8,669
I generally use Javascript as my scripting language along with ASP.

I have noticed that VBscript developers tend to initialize a group of constant global variables a the beginning of a script even though the script may only use that variable once. Since each variable takes up precious memory resources and the constant variable is already a literal string anyway; wouldn't it be better to use the literal strings hard coded into the script or application if only being used once or not at all in some cases, to free up memory resouces in an application.
I agree with you wholeheartedly, ASPDeveloper. To Declare a series of Constant Variables Globally, when used in the context of single usage, is a waste of System Resources. In these cases, it is my opinion that the Variables should be hard coded into the Script/Application.
Jan 9 '08 #3

NeoPa
Expert Mod 15k+
P: 31,660
Just for reference, I'd like to state that I disagree fundamentally with the ideas posted by ASPDeveloper.

Not that I'm saying efficiency is unimportant. Far from it. Simply that code organisation and consistency plays a very important role in code maintenance, and code maintenance is such a supremely important (and criminally undervalued so often) aspect, that this level of code inefficiency is entirely negligible when compared with the relative ease of maintenance that comes with tidy and consistent coding.

I would say pay close attention to ADezii's six tips. These are all worthwhile concepts to take onboard. If you're not doing them already, then start ASAP.
Aug 30 '09 #4

ADezii
Expert 5K+
P: 8,669
@NeoPa
Are we digging up the past, NeoPa? (LOL)
Aug 30 '09 #5

NeoPa
Expert Mod 15k+
P: 31,660
@ADezii
I'm planning to refer to this and a bunch of other good articles ADezii. This invariably means that I visit them (and maybe even add some comments).

I certainly don't see popular articles as dead threads. If any good ones appear dead or old, then possibly it's time to change that ;-)
Aug 31 '09 #6

ADezii
Expert 5K+
P: 8,669
@NeoPa
Just thought that you liked my Articles! (LOL)
Aug 31 '09 #7

Expert 100+
P: 1,287
I have to agree with NeoPa. ASPDeveloper seems to have missed one of the main points of using constants, even with the (negligible) cost to "precious memory resources".
Aug 31 '09 #8

Megalog
Expert 100+
P: 378
Excellent tips here, but what about the tools out there that allow one to do these things quicker? Here is a listing of the FREEWARE VB Editor tools I use to streamline my code. These tools help with almost all of the tips ADezii posted, by automating processes or allowing one to make lightning-fast corrections.

I've been using these for a few years now, and I'd be absolutely lost without them now. I've posted the homepages, names, and the description from each tool as they are on their homepages.. but these are very general descriptions. Detailing what these can all do would take quite a while.. its' best to just pick them up, install them onto your system, and make sure the toolbars in your VB Editor are visible. These all have Right-Click menu options, as well as detailed setup screens accessible from the toolbars to allow you to further customize the procedures, set defaults, etc.

Office Automation Ltd - Stephen Bullen
http://www.oaltd.co.uk/

Smart Indenter (IndenterVBA.exe v3.5)
http://www.oaltd.co.uk/Indenter
"These COM Addins for the Office 2000-2003, Excel 97 and Visual Basic 6 IDEs are the latest updates for the popular Smart Indenter utility. It adds the ability to rebuild all the indenting for a VBA procedure, module or project (i.e. indenting after each If, For etc and outdenting before each End If, Next etc.). The routine handles all valid VBA constructs, including line continuations, multi-statement lines and conditional compilation items and works within all of the Office products and any other VBA6 host."

VBETools.exe v2.0
http://www.oaltd.co.uk/VBETools

"This COM Add-in adds a number of features to the Office VBE, including:
  • Close all open windows in one click
  • Display the size of the active module on the toolbar
  • Rename controls and update the code that uses them
  • Modify the Tools > References dialog to display the full path of any references
  • Accurately Move and size userform controls pixel-by-pixel
More information and screen shots can be found on the VBE Tools page."

MZ-Tools
http://www.mztools.com


MZ-Tools 3.0 for Visual Basic 6.0, 5.0 and VBA (40+ Features)
"MZ-Tools 3.0 is a freeware add-in for Visual Basic 6.0, Visual Basic 5.0 and the Visual Basic For Applications editor (provided by a VBA-enabled application such as those in Office 2000-2007) which adds several productivity features to the IDE.

MZ-Tools is very easy to use. It provides a main menu, a toolbar, handy context menus and customizable shortcuts to access its features, which are detailed in the Features section.

You can customize several features of MZ-Tools to meet your development standards (data type prefixes, template for procedure headers, template for error handler, etc.) or your personal preferences (user name, shortcuts, etc.)
For your convenience, MZ-Tools has been localized in the following languages: English, Spanish, French, Italian, German and Portuguese (Portugal).

MZ-Tools will allow you to enjoy the following benefits during the development of your applications:
  • To write code faster: There are features that will allow you to insert exception handlers, snippets of code, etc. with a single mouse click, keyboard shortcut or expansion keyword, and to use assistants to create new procedures, message boxes, connection strings, etc.
  • To find code faster: With the enhanced Find feature of MZ-Tools, all the results are shown in a hierarchical tree inside a dockable window that allows you to remove occurrences that are not of interest. Other features allow you to find all code locations that call a given procedure, to keep a list of favorite procedures, etc.
  • To design forms faster: There are features that will allow you to apply default properties to a control when it is added to a form, to set the TabIndex property of all the controls of a form with one click, etc.
  • To document your code faster: There are features that will allow you to insert headers (to a procedure, class or file) with a single mouse click or keyboard shortcut. These headers are customizable and allow the use of predefined variables (such as the procedure name) or user-defined variables. Furthermore, other features will generate documentation about your source code in XML and HTML formats.
  • To ensure the quality of your code and applications: There are features that can sort code, add line numbers for error handlers, code reviews that can detect dead code, review the TabIndex or access keys of your controls, review forbidden or mandatory text, etc. Even better, from version 4.0 for Visual Studio .NET onwards you can use the MZ-Tools SDK to write your own review operations with very little effort.
  • And many more features (40+ in each toolset) to make coding more enjoyable by eliminating the tedious tasks!"

If anyone else has any good freeware tools they've found they simply cant live without, I'd like to hear about them.

Also, I've been using these extensively in Office 2007, and have verified they work fine in Office 2010. So even though most of these utilities havent been updated since 2003, dont worry about compatability.
Sep 17 '09 #9

ADezii
Expert 5K+
P: 8,669
Great job Megalog, looks like some very useful, practical, and interesting Resources that you have listed here. Thanks for the effort.
Sep 18 '09 #10

P: 3
I'm with you on all but #5, I can't really argue against it, but starting in other languages I'm just not a fan! I'd also add always use early binding so that you actually get info on the objects your using and can detect runtime errors. Granted most ppl should swap to late binding for compatibility, my working environment is over 20k systems with identical operating images, so not a concern for me, in fact I'm pretty sure performance is better for early binding.

And also learn to use the tools you have, I used to constantly complain about it not being a real dev environment but when I actually decided to look, you can do quite a bit. Ive seen a lot of inefficient code where an existing method already does it, suggesting not using object browser. If VBA is your first experience coding you MUST learn about watches and the local window
May 4 '13 #11

100+
P: 547
Thx for the good work that you guys are doing. I still visit your site almost on a daily basis, to pick up tips on how to improve certain aspects of my own applications, when solutions are given to other subscribers.
May 5 '13 #12

NeoPa
Expert Mod 15k+
P: 31,660
d0wns3t:
And also learn to use the tools you have, I used to constantly complain about it not being a real dev environment but when I actually decided to look, you can do quite a bit. Ive seen a lot of inefficient code where an existing method already does it, suggesting not using object browser.
I like that comment. Clearly intelligence and experience lie behind that one :-)

I'm a heavy user of line continuations myself, as I believe readability to be so important in code, but it's a suggestion. If you can keep the lines visible without needing to scroll in other ways then there's no need to use it I suppose.
May 10 '13 #13

twinnyfo
Expert Mod 2.5K+
P: 3,358
ADezii,

I know this is an old article, but I would like some clarification on 6 above: "Declare Variables and Constants at the Beginning of a Procedure".

As a general rule, my declarations always come first in my procedures. However, there are circumstances in which I list a few declarations first, then test the data of the current situation to see if the rest of the code will be executed. For example, I may only want to create a recordset, cycle through it, and execute certain actions if certain criteria are met first. In this case, I don't declare the recordset, and its associated variables which would be needed in the rest of the code until I have first determined that the code should execute.

Since I still consider myself a newbie to Access (only about 15 years of experience), is there an advantage or disadvantage (other then the obvious economy of system resources) in using one way over the other.

My initial thought, when writing code like this, is that if I am not going to use a recordset, I shouldn't declare it. But, I may be overlooking something obvious.

Thanks for your article and your thoughts!

Grace and Peace,
Twinnyfo
Nov 4 '13 #14

NeoPa
Expert Mod 15k+
P: 31,660
I would suggest that in such a situation it generally makes sense to encapsulate the later work into a separate procedure.

Nevertheless, I don't believe that space is allocated at the point where the Dim lines are confronted, but when a procedure is invoked. The compiler (I'm a little rusty on this so may be proven wrong) scans the code and prepares space for all variables declared within the procedure - regardless of where the Dim lines are found.

Non-static variables are created on the processor stack, and all but the very basic ones are simply pointers anyway.
Nov 4 '13 #15

twinnyfo
Expert Mod 2.5K+
P: 3,358
NeoPa,

Thanks again. You provide some incredibly helpful info the average user wouldn't know.

Peace!
Nov 4 '13 #16

NeoPa
Expert Mod 15k+
P: 31,660
Always a pleasure Twinny.

I forgot to say that, regardless of all the other points, the benefit of the code being more standard, and easily readable by others used to such standards, far outweighs (IMHO) any resource costs that might have accrued if it didn't work that way.

Most experienced programmers will not send blessings your way if left working with code that doesn't conform to the basic standards. This is one of those. Another common one is code that is either not indented, or far worse, indented incorrectly.

Peace back to you :-)
Nov 4 '13 #17