Something that comes up from time to time in my projects is the need for a very random string of numbers and letters. In an application that needs something like this, it's easy to think that you can count on using a long string to ensure uniqueness, but I've always felt that this was a dangerous assumption, particularly in an application that scales. In my projects with the OutSystems Agile Platform using my SaaS Framework, I found the need for this in more than one place, so what I've done is made a simple system to give me random strings that are sure to be unique.
You may be wondering about the uses of such a system. In my SaaS Framework it is a core piece of the password reset system. It sends an email to the user with a unique string in the link to complete the password, which is used to identify the request, and validate things like who the user is, and that the password reset request has not already been completed. In such a situation, it would be a major security risk to send out an easily predicted identifier. I also use the system for providing unregistered users access to a restricted piece of information, such as emailing a customer a quotation for work to be performed. Again, this is a situation in which you cannot afford to have the data identifier be predictable, but at the same time you cannot validate the user's identity.
Creating the strings
Agile Platform comes with a "GeneratePassword" function that creates the strings for you. It accepts an Integer to specify the length and a Boolean that allows you to have it return only numbers.
In order to make sure that the results are unique, I created an Entity called UNIQUE_STRING to store what was already made. Next, I made an Action that accepts a length and a Boolean flag for numbers only. The Action runs GeneratePassword passing in the matching input parameters, and then checks the database to make sure that what was created is not already there. Once it has a unique entry, it adds it to the database, and then returns the ID of the created Entity.
I chose to use the ID of the Entity and not the actual value for the Action's output because I want the consumers to have the option of deleting the entry if it is ever appropriate. For example, in a situation where the string identifies a temporary or disposable item (like a filename), then it makes perfect sense to get rid of it when you are done. After all, why have a database filled with data you will never need again and has no business value?
More about the Agile Platform
Justin James is the Lead Architect for Conigent.