PeopleCode | Writing generic code that accepts any rowset as a parameter
A. The Power of Reusable Code
The majority of customisations are targeted for a specific page and a specific record, with this information entered directly into the code. Although this addresses the immediate requirement, the code has limited application elsewhere in the system. Most developers often feel compelled to move onto the next piece of work as soon as possible, but if more time was spent on writing reusable code, this would help to save time in the future. Reusable code also tends to be less buggy.
In the example below, we will write a generic function that accepts any rowset object as a parameter. The purpose of the function is to loop through the rowset checking for duplicate rows. If a duplicate is found, the entire row is removed from the rowset.
B. RemoveDuplicateRows Function
Firstly, here’s the entire function in its entirety:
Function RemoveDuplicateRows(&in_rowset As Rowset); Local integer &i, &j; Local Record &Next_Rec, &Compare_Rec; /* Loop through all rows in the rowset, apart from the final row */ For &i = 1 To &in_rowset.ActiveRowCount - 1 /* Set a record object equal to the current row */ &Next_Rec = &in_rowset.GetRow(&i).GetRecord(@("Record." | &in_rowset.DBRecordName)); /* Loop through all remaining rows in the rowset. Do this backwards in case a delete needs to be performed */ For &j = &in_rowset.ActiveRowCount To &i + 1 Step - 1 /* Set a record object equal to the current row */ &Compare_Rec = &in_rowset.GetRow(&j). GetRecord(@("Record." | &in_rowset.DBRecordName)); /* Check to see if the two records are an exact match */ If &Next_Rec.CompareFields(&Compare_Rec) Then /* Match found - delete row from the rowset */ &in_rowset.DeleteRow(&j); End-If; End-For; End-For; End-Function;
C. Constructs for Generic Code
In the above function, note the following pieces of code in particular:
Dynamic object naming has been used in the form of the ‘@’ symbol followed by the record name of the current rowset. This means we do not care which record has been used. The exact record name will be set at run-time.
&Next_Rec = &in_rowset.GetRow(&i). GetRecord(@("Record." | &in_rowset.DBRecordName));
The Rowset property ‘DBRecordName’ retrieves the name of the record used in the rowset
&Next_Rec = &in_rowset.GetRow(&i). GetRecord(@("Record." | &in_rowset.DBRecordName));
The CompareFields record method compares the values of one record to another. In this way, it makes no difference how many fields are included in the record.
If &Next_Rec.CompareFields(&Compare_Rec) Then
See Also:
Tip 016: Dynamic Object Names