April 24, 2009

QTP variable name conventions

When you start with a new test automation project, your code is conveniently arranged and you still have a clear overview over the locations and naming of variables and functions. But later on it will become a disaster if you don’t manage it a little bit.
That is why I wrote a name convention article. It is not an official how-you-should-do-it document, it is just the way I do things and written from experience.

' Public and Private constants in capitals
Public Const MOUSEEVENTTF _MOVE = 1
Private Const APPLICATION_MAIN_WINDOW = "name:=My Application"

' Functions, Subs and local variables in lowerCamelCase
Public Function myCustomFunction(thisVariable, thatVariable)

     ' Variables with a known type can be declared with the type abbreviation in front of it
     Dim arrStaticArry(5), objFile, intCounter, blnReadOnly

     ' Variables with a unknown type are declared without a type abbreviation, This is also applicable for variables used in self commentary code.
     Dim customContainer, fileWasFound

     ' Consts with local scope are declared with the same format as variables
     Const cannotBeChanged = True

End Function

' Classes in UpperCamelCase. In QTP I use the cls_ tag in front of it for reasons explained later.
Class cls_EventListener

     ' Public variables are in UpperCamelCase too
     Public BufferLength

     ' Private variables with class scope are lowerCamelCase with an underscore behind it
     Private updateCounter_, eventNumber_

     ' Properties, Subs and Functions (public and private) are all in UpperCamelCase
     Public Property Get EventNumber()
         EventNumber = eventNumber_
     End Property
End Class

In QTP, a class gets a local scope. To make it global, you have to add a function returning that class. As a side effect, this gives you the opportunity to initialize the class. Of course you have to add an init method to your class if you do it this way.

Public Function [new EventListener](initializationParameters)
     Set [new EventListener] = new cls_EventListener
     [new EventListener].Init(initializationParameters)
End Function

Now, you can set a new class with the following code in another library:
Set EventListener = [new EventListener]("codebase:=Unicode")

Side note: The square brackets around a variable lets you enter every character for a variable, including spaces, special characters etc. If you find that inconvenient, you can use an underscore: new_EventListener to mimic normal VB functionality.
I use the square brackets when I want to express importance for example:

' Call the main routine of this script:
[___ !MAIN! ___]

' Or to enjoy my co workers (and to see if they ever peer review my code):
Dim [ O\-<>-/O ], [ ¿Que? ]

1 comment:

Stefan Thelenius said...

Hi,

Good article!

Regards

/Stefan