|
|
Naming Conventions Naming Conventions is an extremely important concept, with advantages that spread across all aspects of your Access project. Code is easily readable and can be summarized nearly at a glance, functionality of your code can be based upon the conventions you choose to use, and a plethora of bugs and errors (ranging from annoying to serious) can be avoided. After establishing a strong data foundation, the faithful use of a naming convention might be one of the most important things you can do for your project. As a testimony to the sanity levels that can maintained through the use of naming conventions, consider the the start to finish development time for a mid-sized project being handled by a developer who employs naming conventions to one who doesn't. Naming conventions can enhance the readability of code and expressions, which in turn can reduce development time significantly. Furthermore, the (re)learning curve time is reduced when the project is revisited.
[edit] The Basic Concept: What It IsAn Naming Convention is merely a system that is used to differentiate one item from another. Generally this is employed through the use of prefixes added to the names of the item. For every object (form, report, label, control, field, table, etc etc) and every variable in your code, there should ideally be some sort of prefix to indicate what the particular item is. Here's a few examples:
As you can see, the concept of a naming convention is simple. The only difficult part of using one is developing a convention that works for you, and sticking to it. Keep in mind that using different conventions inconsistently throughout a project is almost as bad as using none at all. While it may take some time to develop a good convention, it should be made a priority to do so, and implementation of any changes to it should be attempted across the entire scope of the project instead of in specific areas. While you can get away with small variations in the convention here and there, a multitude of differences throughout the project becomes a complete mess to deal with later...
[edit] Common Naming Conventions
[edit] Objects
[edit] Major Objects
[edit] Minor Objects
[edit] Variables & Code
Further prefixing may be used to differentiate different types of objects. For example, jtbl for Junction Tables, ltbl for Local tables, ttbl for Temporary tables, etc..
[edit] Links
[edit] Specific Reasons for using Conventions
[edit] Reserved WordsReserved words are, as implied, words that have special meaning in Access. Requiring variable declaration in the code (adding Option Explicit to the top of every code module) is probably the single most important thing you can do to avoid errors arising from typos and the use of reserved words, as compiling the code will identify many such anomalies. However, not every such error will be detected when you compile the code, so naming conventions are another strong line of defense against inadvertent use of a reserved word that can lead to errors ranging from annoying (something very strange is going on and I have no idea why....) to catastrophic. Errors that are not detected by compiling the code can be especially difficult to identify, as they often manifest themselves as odd happenings with no discernable explaination, and often without an actual error message. Things just don't work as expected. This is perhaps the most important reason for using naming conventions. With a good convention applied, no name, label, variable or other identifier will ever be without a prefix of some sort or another. It is worth noting that many constants include prefixes including ac or vb, and functions including StrComp and StrConv use str as a prefix, so care still must be taken even when using a naming convention. However, a consistent naming convention significantly reduces the chance of conflicts with reserved words. [edit] ReadabilityMuch to the dismay of leading manufacturers of over-the-counter headache medicines, naming conventions are a Godsend for the developer when it comes to understanding code. When a developer uses consistent naming conventions throughout a project, another adept developer can, at a glance, come up with an educated synopsis of the task and the resources being used to complete that task. Without a naming convention, this can take hours to decipher. If you are a novice programmer and want others to examine your code (through a newsgroup, forum, or paid profession services), you will be greatly appreciated (and may save a lot of money) through the use of a naming convention. This really cannot be stressed enough... many can testify that there is nothing worse than trying to decipher a large chunk of code with no guidance from a naming convention. And, we all know that at some point down the road, we will end up editing and updating our projects. Even the orignal developer of an application rarely can remember everything they were doing at the time of development... naming conventions go miles towards helping the developer quickly get back into the swing of things. [edit] FunctionalityThe last thing to note here is the effects that a naming convention may have on the functional development of a project. With good practices in naming, we can use this to our advantage greatly during development, automating a number of tasks that might otherwise add up to long hours of manual work (and who wants to work when they don't have to?)
[edit] Spaces & Special CharactersIn short: Don't use them!!! While Access now allows us to use spaces in field and object names, it is highly recommended to avoid them. Use CamelCase instead and save yourself tons of time and hairpulling from the inevitable errors that come with using spaces in names. Special characters should be a given... don't even try this (at home or anywhere else) The characters to be most avoided are: ! @ # $ % ^ & * ( ) ? > < + = ' "; : - ~ `\ | [ ] { }
[edit] Examples of Development FunctionalityAs previously mentioned, Naming Conventions can be a great aid in automating some development tasks. Here's at least one example: [edit] Setting Control Names in Forms (and Reports)Let's suppose that part of your convention is to prefix all field names with "fld" (after all, you need to put something there so you don't wind up with field names like the reserved word "Name"). When you create a form through the use of a wizard, or when you add fields by dragging and dropping from the field list, Access will automatically name the controls for the said field with the same name as the field. This is all well and good, except that now the AccessField in the underlying form/report has the same name as the corresponding control, and there is reason for us to want them differentiated. The function below is an example of how one can utilize a naming convention to convert the "fld" prefix of the Field to a "ctl" prefix of Controls... CODE '============================================================================== ' NAME: fConvertControlNames ' DESC: Converts the prefix on Controls for a new form ' RETURNS: Boolean: False if function failed ' ARGS: Optional strFormName: Name of the form to perform the operation on ' If ommited you will be prompted for the form name ' Optional bNotifyCompletion: notify when completed ' '============================================================================== 'ErrStrV3.01 Public Function fConvertControlNames( _ Optional strFormName As String = "", _ Optional bNotifyCompletion As Boolean = True _ ) As Boolean On Error GoTo Error_Proc Dim Ret As Boolean '========================= Dim strFieldPrefix As String Dim strControlPrefix As String Dim iLenFieldPrefix As Integer 'length of the field prefix Dim frm As Form Dim ctl As Control Dim bFlag As Boolean 'loop flag Dim i As Integer 'loop counter & msgbox return '========================= 'change these to match your convetions strFieldPrefix = "fld" strControlPrefix = "ctl" 'init field prefix length iLenFieldPrefix = Len(strFieldPrefix) 'check for a provided formname, prompt if none If Len(strFormName) = 0 Then strFormName = InputBox("Please enter the Form Name:") End If 'make sure they entered something If Len(strFormName) = 0 Then MsgBox "No Form Name supplied, the function will exit" GoTo Exit_Proc End If 'make sure the form exists bFlag = False For i = 0 To CurrentProject.AllForms.Count - 1 If CurrentProject.AllForms(i).name = strFormName Then bFlag = True Next If Not bFlag Then MsgBox "The Form Name you entered (" & strFormName & _ ") does not exist!", vbCritical GoTo Exit_Proc End If 'if the form is open prompt the user to close it... For Each frm In Forms If frm.name = strFormName Then i = MsgBox("The form " & strFormName & " is open and will need " & _ "to close to perform the operation. Would you like " & _ "to close the form and continue? Changes will be " & _ "saved...", vbYesNo, "Close Form?") If i = vbYes Then DoCmd.Close acForm, strFormName, acSaveYes Else MsgBox "Function Cancelled, no changes made" GoTo Exit_Proc End If End If Next frm Set frm = Nothing 'now that we know the form exists and is not in use, we'll do 'what we came to do... 'open form in hidden design view DoCmd.OpenForm strFormName, acDesign, , , , acHidden 'loop the controls, checking for the field prefix and converting when found For Each ctl In Forms(strFormName) If Left(ctl.name, iLenFieldPrefix) = strFieldPrefix Then ctl.name = Replace(ctl.name, strFieldPrefix, strControlPrefix, 1, 1) End If Next ctl 'save and close the form DoCmd.Close acForm, strFormName, acSaveYes 'notify if required If bNotifyCompletion Then MsgBox "Conversion complete" End If Ret = True '========================= Exit_Proc: Set frm = Nothing Set ctl = Nothing fConvertControlNames = Ret Exit Function Error_Proc: Ret = False Select Case Err.Number Case Else MsgBox "Error: " & Trim(Str(Err.Number)) & vbCrLf & _ "Desc: " & Err.Description & vbCrLf & vbCrLf & _ "Module: zDEVmodTools, Procedure: fConvertControlNames" _ , vbCritical, "Error!" End Select Resume Exit_Proc Resume End Function There, by utilizing naming conventions and running a single function from the immediate window or macro, we can save ourselves quite some amount of time by not having to manually edit each control name to differentiate between Access Fields and Controls.
|
| This page has been accessed 4,788 times. This page was last modified 11:13, 10 April 2013 by Mark Davis. Contributions by Jack Leach and BruceM Disclaimers |