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:
Solution 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.
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.
what a douche
ReplyDeleteOMG! 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
ReplyDeleteTim, 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!
ReplyDeleteI can't help but think that solution A is actually better :D
ReplyDeleteB = 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...
Yes Jani... it's all tongue-in-cheek. A is better :)
ReplyDeleteIronically, 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