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

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 Shoulders Composition doesn’t happen in a vacuum. Bach wa

Learning Prolog

I'm not quite sure exactly I was searching for, but somehow I serendipitously stumbled upon the site learnprolognow.org a few months ago. It's the home for an introductory Prolog programming course. Logic programming offers an interesting way to think about your problems; I've been doing so much procedural and object-oriented programming in the past decade that it really took effort to think at a higher level! I found the most interesting features to be definite clause grammars (DCG), and unification. Difference lists are very powerful and Prolog's DCG syntax makes it easy to work with them. Specifying a grammar such as: s(s(NP,VP)) --> np(NP,X,Y,subject), vp(VP,X,Y). np(np(DET,NBAR,PP),X,Y,_) --> det(DET,X), nbar(NBAR,X,Y), pp(PP). np(np(DET,NBAR),X,Y,_) --> det(DET,X), nbar(NBAR,X,Y). np(np(PRO),X,Y,Z) --> pro(PRO,X,Y,Z). vp(vp(V),X,Y) --> v(V,X,Y). vp(vp(V,NP),X,Y) --> v(V,X,Y), np(NP,_,_,object). nbar(nbar(JP),X,3) --> jp(JP,X). pp(pp(PREP,N

What's Wrong with OOP

Proponents of Object Oriented Programming feel the paradigm yields code that is better organized, easier to understand and maintain, and reusable. They view procedural programming code as unwieldy spaghetti and embrace OO-centric design patterns as the "right way" to do things. They argue objects are easier to grasp because they model how we view the world. If the popularity of languages like Java and C# is any indication, they may be right. But after almost 20 years of OOP in the mainstream, there's still a large portion of programmers who resist it. If objects truly model the way people think of things in the real world, then why do people have a hard time understanding and working in OOP? I suspect the problem might be the focus on objects instead of actions. If I may quote from Steve Yegge's Execution in the Kingdom of Nouns : Verbs in Javaland are responsible for all the work, but as they are held in contempt by all, no Verb is ever permitted to wander about