Using Maps in PeopleCode

Maps, also known as hashmaps, are key-value pairs that let you store and retrieve data using a key. I wrote PeopleCode for years without using one, but after jumping back and forth between PeopleCode and Java, I can't write any code without maps.

What's great about maps is their simplicity. It's not that they do anything fancy, they just make writing code easier and make that code easier to understand. Wikipedia provides a good example of a map—a dictionary. The words are the keys and the definitions are the values.

One example I've used maps for is caching. If you've got a database lookup that occurs for each row in consideration, but there are only a couple of distinct lookup values, cache those values in a map instead of querying the database each time. For each row, check to see if the lookup is in the map: if it is, return it; if it is not, look it up from the database then store it in the map and return it.

Maps start to get more powerful when you realize you can store anything in one. Another example I used a map for is a totals grid. I had a list of items (a sales order or a purchase order) and wanted to display the total quantity for each item. The keys to my map were a concatenation of the BU and Item Id. The value returned by the map was the row representing that item in the totals grid.

Without the map I would have done a loop through the totals rowset each time, looking for the row in question. With the map, it was one line of code.

Can't find the Map object in the PeopleTools API? That's because it's not a delivered class. Instead, it's one that was added by application developers and must be imported to be used. In the HR database, look for application package HRTR_UTILITIES. The classes there refer to maps as hashtables. Check it out, it's good code with good comments.

Here's the public class declaration for StringHashtable, which uses strings for both the keys and values:

 class StringHashtable
   method StringHashtable();
   method Put(&key As string, &value As string);
   method Get(&key As string) Returns string;
   method GetKeys() Returns array of string;
   method IsKey(&key As string) Returns boolean;
   method GetValues() Returns array of string;


Excellent find!

Posted by Mike Putnam on November 11, 2009 at 02:15 PM PST #

Post a Comment:
Comments are closed for this entry.