Cameron Stokes's Blog

[ 'technologist', 'beer lover', 'foodie', 'traveler' ]

Short ID Generator in Groovy

On my latest side project I needed to create IDs for items in a database, but without using a database sequence or artificial counter. I generally would use a UUID but for this project I wanted to minimize the size of the identifier to save on space and make the IDs usable similar to a URL shortener service.

Here’s what I whipped up in Groovy:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class IDUtils {

  def NUMBER_OF_CHARS = 5
  def CHARS = ('0'..'9') +
          ('a'..'h') +
          ('j'..'k') +
          ('m'..'z') +
          ('A'..'H') +
          ('J'..'K') +
          ('M'..'Z')

  def random = new Random()

  def generateID() {
    def id = ""
    for ( i in 1..NUMBER_OF_CHARS ) {
      id += CHARS[random.nextInt(CHARS.size())]
    }
    return id
  }

}

CHARS specifies the available character set and NUMBER_OF_CHARS specifies the length of the ID generated. I specifically omit i and l to cut down on confusion and readability issues across different fonts. The output of generateID() is an ID in the form of 9reaZ, CfrDS, a22mE, etc. With this character set and 5 characters in length there are 601,692,057 combinations available.

Tech

Comments