VBscript: method chaining

Method chaining is a common syntax for invoking multiple method calls in object-oriented programming languages which allows you to to refer to the specific instance of a class having several method calls. For more information, please refer to Wikipedia article Method chaining. Imagine the situation when you have some GUI test in your HP UFT and apart of actions in GUI and verification you need to get data from database. Most probably you have a query with parameters, for example select * from customers where name = 'John' and surname = 'Doe'. An now you want to set values of parameters in the query. How to implement it in VBScript? We can do it and we are going to use method chaining for this.

First of all create a new class. Private field to sqlQuery to keep query, method SetValue (we have to use this method to set value of sqlQuery field since class constructor is not available in VBScript), Build method which is going to do the job to modify query.

Class TestClass

    Private sqlQuery

    Public Function SetValue(ByRef value)
        sqlQuery = value
        Set SetValue = me
    End Function

    Public Function GetValue()
        getValue = sqlQuery
    End Function

    Public Function Build(Byref placeHolder, ByRef value)
        value = Replace(sqlQuery, placeHolder, value)
        Set Build = me
    End Function

End Class

Keyword Me is intended to return reference to current instance of a class. It can be considered as this in Java or self in Puthon.

Now we need a function to initialize sqlQuery (sort of constructor in our case):

Public Function InitTestClass(initialValue)
    Set InitTestClass = new TestClass
    call InitTestClass.SetValue(initialValue)
End Function
  
Ok, we are ready to go. To make it shorter simply define SQL query as a string (and you feel free to put it into any data source available in HP UFT: excel, xml, whatever).


Dim mySQLquery
Set mySQLquery = InitTestClass("select * from customers where name = '${customer_name}' and surname = '${customer_surname}';")
MsgBox mySQLquery.Build("'${customer_name}'", "John").Build("'${customer_surname}'", "Doe").GetValue()  

And we are done! As a conclusion we can say that in some cases method chaining adds 'fluent' syntax to your VBscript code and in some cases may reduce amount of code. On the other hand, misusing of method chaining may lead to obfuscating your code and make it difficult to debug.   

Comments