473,320 Members | 1,872 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes and contribute your articles to a community of 473,320 developers and data experts.

A 6-Pack of Good Programming Style Hints

ADezii
8,834 Expert 8TB
  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
16 10811
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
8,834 Expert 8TB
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
32,556 Expert Mod 16PB
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
8,834 Expert 8TB
@NeoPa
Are we digging up the past, NeoPa? (LOL)
Aug 30 '09 #5
NeoPa
32,556 Expert Mod 16PB
@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
8,834 Expert 8TB
@NeoPa
Just thought that you liked my Articles! (LOL)
Aug 31 '09 #7
ChipR
1,287 Expert 1GB
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
378 Expert 256MB
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
8,834 Expert 8TB
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
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
neelsfer
547 512MB
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
32,556 Expert Mod 16PB
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
3,653 Expert Mod 2GB
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
32,556 Expert Mod 16PB
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
3,653 Expert Mod 2GB
NeoPa,

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

Peace!
Nov 4 '13 #16
NeoPa
32,556 Expert Mod 16PB
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

Sign in to post your reply or Sign up for a free account.

Similar topics

7
by: KPB | last post by:
I have an O'Reilly Safari Online subscription. I decided to check out this book(C++ Templates) and am half way through it. For those of you who read this one, I don't know what you thought about...
16
by: E. Robert Tisdale | last post by:
C++ Programming Style Guidelines http://geosoft.no/development/cppstyle.html I think that these guidelines are almost *all* wrong. For example: 11. Private class variables should have...
8
by: Todd Smith | last post by:
I'm wondering if anyone knows where I can learn a good programming method for creating windows apps. I'm just starting to learn windows programming with MSVC++ 6.0. I want to learn low level...
43
by: Sensei | last post by:
Hi! I'm thinking about a good programming style, pros and cons of some topics. Of course, this has nothing to do with indentation... Students are now java-dependent (too bad) and I need some...
13
by: Mark | last post by:
Hi This is a fairly generic question about programming style and to a certain extent garbage collection. I have some methods that I write to text logs, the event log etc at various places in...
0
by: MSFCLIPPER | last post by:
there are now new open source project presents new programming style design / paradigm vs OOP we invite all programmers to participate in this project project site :...
10
by: dydx31 | last post by:
Here is a simple program that I wrote: //This program takes in various inputs. //It calculates if the current balance exceeds the credit limit. //Programmer: Nathan D. Brown //Date: ...
14
by: Astley Le Jasper | last post by:
I'm still learning python and would like to know what's a good way of organizing code. I am writing some scripts to scrape a number of different website that hold similar information and then...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.