Skip to main content

Pop Quiz

Here's a little test to separate the serious coders from the cut-and-paste script kiddies. Given the need to generate an arbitrarily long string consisting of random alpha-numeric characters, which solution is best?

Solution A:
function randomString($len) {
    $chars  = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" .
              "abcdefghijklmnopqrstuvwxyz" .
              "0123456789";
    $rndMax = strlen($chars) - 1;
    $str = "";
    while ($len-- != 0) {
        $str .= $chars[rand(0, $rndMax)];
    }
    return $str;
}

$str = randomString(8);
echo "$str\n";

Solution B:
class RandomSequenceIterator implements Iterator
{
    protected $seqMembers;
    protected $key;
    protected $limit;

    public function __construct() {
        $this->setMembers(null)
             ->setLimit(0)
             ->rewind();
    }

    protected function setMembers($strValue) {
        $this->seqMembers = $strValue;
        return $this;
    }

    protected function getMembers() {
        return $this->seqMembers;
    }

    protected function setLimit($intValue) {
        $this->limit = $intValue;
        return $this;
    }

    protected function getLimit() {
        if (empty($this->limit)) {
            return 0;
        }
        else {
            return $this->limit;
        }
    }

    public function current() {
        $index = rand(0, strlen($this->getMembers()) - 1);
        return substr($this->getMembers(), $index, 1);
    }

    public function valid() {
        return $this->key() < $this->getLimit();
    }

    public function key() {
        return $this->key;
    }

    public function next() {
        $this->key++;
    }

    public function reset() {
        $this->rewind();
    }

    public function rewind() {
        $this->key = 0;
    }
}

class RandomCharacterSequenceGenerator extends
RandomSequenceIterator
{
    public function setChars($strValue) {
        $this->setMembers($strValue);
        return $this;
    }

    public function getChars() {
        return $this->getMembers();
    }

    public function generate($limit) {
        $strBuffer = "";
        $this->setLimit($limit);
        foreach ($this as $char) {
            $strBuffer .= $char;
        }
        return $strBuffer;
    }
}

abstract class RandomGeneratorBase
{
    protected static $instance;
    protected static $generator;

    protected function __construct() {
        self::$generator = new
            RandomCharacterSequenceGenerator();
    }

    // abstract public static function getInstance();
    public static function getInstance() {
        if (empty(self::$instance)) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    public function generate($limit) {
        return self::$generator->generate($limit);
    }
}

class RandomNumericStringGenerator extends RandomGeneratorBase
{
    const VALID_MEMBERS = "0123456789";

    protected function __construct() {
        parent::__construct();
        self::$generator->setChars(self::VALID_MEMBERS);
    }

    public static function getInstance() {
        if (empty(self::$instance)) {
            self::$instance = new self();
        }
        return self::$instance;
    }
}

class RandomUpperCaseAlphaStringGenerator extends
RandomGeneratorBase
{
    const VALID_MEMBERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    protected function __construct() {
        parent::__construct();
        self::$generator->setChars(self::VALID_MEMBERS);
    }

    public static function getInstance() {
        if (empty(self::$instance)) {
            self::$instance = new self();
        }
        return self::$instance;
    }
}

class RandomLowerCaseAlphaStringGenerator extends
RandomGeneratorBase
{
    const VALID_MEMBERS = "abcdefghijklmnopqrstuvwxyz";

    protected function __construct() {
        parent::__construct();
        self::$generator->setChars(self::VALID_MEMBERS);
    }

    public static function getInstance() {
        if (empty(self::$instance)) {
            self::$instance = new self();
        }
        return self::$instance;
    }
}

class RandomMixedCaseAlphaStringGenerator extends
RandomGeneratorBase
{
    protected function __construct() {
        parent::__construct();
        self::$generator->setChars(
           RandomUpperCaseAlphaStringGenerator::VALID_MEMBERS .
           RandomLowerCaseAlphaStringGenerator::VALID_MEMBERS);
    }

    public static function getInstance() {
        if (empty(self::$instance)) {
            self::$instance = new self();
        }
        return self::$instance;
    }
}

class RandomMixedCaseAlphaNumericStringGenerator extends
RandomMixedCaseAlphaStringGenerator
{
    protected function __construct() {
        parent::__construct();
        self::$generator->setChars(
            RandomNumericStringGenerator::VALID_MEMBERS .
            self::$generator->getChars());
    }

    public static function getInstance() {
        if (empty(self::$instance)) {
            self::$instance = new self();
        }
        return self::$instance;
    }
}

$str = RandomMixedCaseAlphaNumericStringGenerator
       ::getInstance()
       ->generate(8);
echo "$str\n";
If you managed to scroll down this far, congratulations! You are a true programmer who knows the correct answer is B.

Solution A is a good example of unorganized spaghetti-code. It "works" but it's amateurish. A uses only language-primitives-- none of the advanced, enterprise architecture concepts embodied in Solution B. It is certainly not flexible. (What if one changed the requirements to generate a random string of only digits, for example?)

Solution B is much more organized, encapsulated, and extensible. Object-oriented code models the way things are in the "real world" so it's easier to conceptualize what the code is doing. The problem is broken down into several smaller, more manageable ones, and uses interfaces, abstract classes, and inheritance to eliminate redundant code, facilitate better organization, and foster code-reuse. Understanding existing code is an important part of programming and the liberal use of design patterns such as Singleton and Decorator embody solutions to common problems giving programmers a common vocabulary with higher levels of abstraction to communicate with one another.

Of course, solution B should only serve as an example and not be used as-is in a production environment. Exceptions should be used, but are omitted here for the sake of brevity. And the actual invocation to generate the random string could probably be further encapsulated and abstracted by implementing the Factory design pattern and maybe the Registry pattern-- one would query the registry for a value object to pass to the factory, and in turn the factory would determine which type of generator to return: random uppercase alpha, random numeric, mixed case, etc.

Comments

  1. OMG! One time I copy and pasted your entire ego into my curved server. It didn't fit on the 14 peta byte hard drive!!!! jk

    ReplyDelete
  2. Tim, I very much am gladness for that you have turned new leaf in understanding enterprise application. I very much look forward on day when all holy bloat for to rain down like goat blood from sky and shower user with blessing of scalable application. Many blessing!

    ReplyDelete
  3. I can't help but think that solution A is actually better :D
    B = total overkill

    Now, if you actually needed a way to generate varying types of random strings then B might be a better way to go, but I still feel it's a bit complex even for that.

    But then I do get the feeling of sarcasm here and there...

    ReplyDelete
  4. Yes Jani... it's all tongue-in-cheek. A is better :)

    ReplyDelete
  5. Ironically, in all that bloat, you didn't factor out one of the few things that would have actually been useful to factor out: the source of the random numbers. Perhaps someone would want a cryptographically secure random string. Maybe they want to use /dev/random if it's available. Maybe they want to use Mcrypt if it's available. Maybe they want to use an implementation of the Fortuna algorithm. Maybe they want to use a different algorithm of their choosing. In all that bloated OOP, you didn't do one of the few things that would have actually been useful, which leads me to believe that you're trying to mock something you don't understand very well.

    ReplyDelete

Post a Comment

Popular posts from this blog

Geolocation Search

Services that allow users to identify nearby points of interest continue to grow in popularity. I'm sure we're all familiar with social websites that let you search for the profiles of people near a postal code, or mobile applications that use geolocation to identify Thai restaurants within walking distance. It's surprisingly simple to implement such functionality, and in this post I will discuss how to do so.

The first step is to obtain the latitude and longitude coordinates of any locations you want to make searchable. In the restaurant scenario, you'd want the latitude and longitude of each eatery. In the social website scenario, you'd want to obtain a list of postal codes with their centroid latitude and longitude.

In general, postal code-based geolocation is a bad idea; their boundaries rarely form simple polygons, the area they cover vary in size, and are subject to change based on the whims of the postal service. But many times we find ourselves stuck on a c…

Composing Music with PHP

I’m not an expert on probability theory, artificial intelligence, and machine learning. And even my Music 201 class from years ago has been long forgotten. But if you’ll indulge me for the next 10 minutes, I think you’ll find that even just a little knowledge can yield impressive results if creatively woven together. I’d like to share with you how to teach PHP to compose music. Here’s an example: You’re looking at a melody generated by PHP. It’s not the most memorable, but it’s not unpleasant either. And surprisingly, the code to generate such sequences is rather brief. So what’s going on? The script calculates a probability map of melodic intervals and applies a Markov process to generate a new sequence. In friendlier terms, musical data is analyzed by a script to learn which intervals make up pleasing melodies. It then creates a new composition by selecting pitches based on the possibilities it’s observed. . Standing on ShouldersComposition doesn’t happen in a vacuum. Bach was f…

Creepy JavaScript Tracking

I recently began allergy shots so my new Monday morning routine includes me sitting in a doctor's office for 30 minutes (I must wait after receiving the shots and be checked by a nurse to make sure there was no reaction). With nothing else better to do while I waited last week, I started playing around with some JavaScript. This is what I came up with:
<html> <head> <title>Test</title> <script type="text/javascript"> window.onload = function () { var mX = 0,  mY = 0, sX = 0,  sY = 0, queue = [], interval = 200, recIntv = null, playIntv = null, b = document.body, de = document.documentElement, cursor = document.getElementById("cursor"), record = document.getElementById("record"), play = document.getElementById("play"); window.onmousemove = function (e) { e = e || window.event; if (e.pageX || e.pageY) { …