<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Advent Digerati &#187; Code Snippet</title>
	<atom:link href="http://blog.adventdigerati.com/tag/code-snippet/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.adventdigerati.com</link>
	<description>Where Life meets Geek</description>
	<lastBuildDate>Mon, 26 Jul 2010 00:49:02 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>$c is not always $a[&quot;c&quot;]</title>
		<link>http://blog.adventdigerati.com/2009/04/c-is-not-always-ac/</link>
		<comments>http://blog.adventdigerati.com/2009/04/c-is-not-always-ac/#comments</comments>
		<pubDate>Thu, 02 Apr 2009 22:42:54 +0000</pubDate>
		<dc:creator>Zack</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Code Snippet]]></category>

		<guid isPermaLink="false">http://blog.adventdigerati.com/?p=48</guid>
		<description><![CDATA[Today I was tipped off to a certain quirk of PHP, specifically with how it handles Array resources. Every programmer knows, (or should know), the differences between creating a new copy of a variable and making a new reference to the same variable. In PHP, as far as I&#8217;ve known, you never access memory directly. [...]]]></description>
			<content:encoded><![CDATA[<p>Today I was tipped off to a certain <a href="http://blog.adventdigerati.com/2009/02/skill-and-quirks/">quirk</a> of PHP, specifically with how it handles Array resources. Every programmer knows, (or should know), the differences between creating a new copy of a variable and making a new reference to the same variable. In PHP, as far as I&#8217;ve known, you never access memory directly. Thus, trying <code>$v = "hello"; $a = &$v; $b = &$a;</code> does not make the value of <code>$b</code> a byte pointer to the location of <code>$a</code>, but instead a new <i>reference</i> to what <code>$v</code> holds. So, modifying <code>$b</code> means you will implicitly edit <code>$v</code>. To those familiar with PHP, this is understandable and often both acceptable and helpful. (As lazy programmers, we don&#8217;t want to have to remember when we have a reference or an &#8216;original&#8217; copy of a value.)</p>
<p>What I didn&#8217;t know, is that this could get us into a lot of trouble without even expecting it. The problem occurs whenever you try to obtain a reference to an element in a PHP array. Case in point:</p>
<pre>$a=Array("one"=>1, "two"=>2,"three"=>null);
$b = $a["four"];
$c =&#038; $a["five"];</pre>
<p>What do we get if we print the value of <code>$a</code> variables? <code>$a</code> is now
<pre>$a = Array(
  ["a"] => 1,
  ["b"] => 2,
  ["d"] => null,
  ["c"] => &#038;null
)</pre>
<p>WHAT?! What happened to <code>$b</code>? What in the world is a <i>pointer</i> to <code>null</code>? PHP actually created the &#8220;c&#8221; key within my Array, just by referencing it in a <i>read context</i>. Lesson learned: always use <code>isset($a["key"])</code> before attempting to draw from an Array by reference!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.adventdigerati.com/2009/04/c-is-not-always-ac/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>OOP-DBC</title>
		<link>http://blog.adventdigerati.com/2009/02/oop-dbc/</link>
		<comments>http://blog.adventdigerati.com/2009/02/oop-dbc/#comments</comments>
		<pubDate>Fri, 06 Feb 2009 05:03:47 +0000</pubDate>
		<dc:creator>Zack</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Code Snippet]]></category>

		<guid isPermaLink="false">http://blog.adventdigerati.com/?p=36</guid>
		<description><![CDATA[Coming out of high school, it was stressed that good practice makes good composition. One of these pillars of thought was code purity. Purity in the sense that each method should do as it&#8217;s advertised without causing side effects. It&#8217;s not much different than Design By Contract, (DBC) &#8211; a coding technique promoted in The [...]]]></description>
			<content:encoded><![CDATA[<p>Coming out of high school, it was stressed that good practice makes good composition. One of these pillars of thought was code purity. Purity in the sense that each method should do as it&#8217;s advertised without causing side effects.</p>
<p>It&#8217;s not much different than Design By Contract, (DBC) &ndash; a coding technique promoted in <a href="http://www.pragprog.com/titles/tpp/the-pragmatic-programmer">The Pragmatic Programmer</a>, another book I&#8217;m reading for work. The thought is that every method has a contract to which it and other methods &ndash; and in OOP, objects/classes &ndash; abide by. Everyone fulfills their contract, everyone benefits, and the programmer can go home early that night.</p>
<p>The downside, as T.P.P. describes, is that OOP does not lend itself nicely to automatic DBC programming: namely that method inheritance doesn&#8217;t imply contract inheritance. This seems like a relatively small gripe to be made about OOP, in my opinion, especially when a simple coding standard can surmount this problem.</p>
<p>In what I&#8217;ve learned from OOP, good style is to use both public and private methods, and methodologies, to their advantage. This, thankfully, lends itself well to implementing DBC.</p>
<p>As with most of my posts, this one includes an example!</p>
<pre>/**
 * Basic object class, all other classes should extend this
 */
class BaseObject {
    /**
     * Public accessor to the toString() concept
     */
    public function toString() {
        // contract invariants
        $invariants = Array('this'=>$this);
        // contract presumptions
        assert(is_object($this), get_type($this)." is not an Object");

        // inherited method
        $r_val = $this->_toString();

        // contract post assertions
        assert(equals($invariants['this'], $this), get_class($this)."::toString() modified the Object in a read-only context");
        assert(is_string($r_val), get_class($this)."::toString() did not return a String.");

        return $r_val;
    }

    /**
     * Private implementation of the toString() concept
     */
    private function _toSring() {
        $r_val = Array();
        $r_val[] = $this->some_val;

        return implode("\n", $r_val);
    }
}

/**
 * A class which does what it's supposed to do
 */
class GoodObject extends BaseObject {
    /**
     * This function abides by the BaseObject::toString() contract
     */
    public function _toString() {
        $r_val = Array();
        $r_val[] = $this->some_val;
        $r_val[] = $this->other_val;

        return implode("\n", $r_val);
    }
}

/**
 * A mischevious class
 */
class BadObject extends BaseObject {
    /**
     * This function does not abide by the BaseObject::toString() contract
     */
    public function _toString() {
        $r_val = Array();
        $r_val[] = $this->yet_another_val;
        $r_val[] = $this->some_val;

        return $r_val;
    }
}</pre>
<p>So we can see that it&#8217;s not too hard to notice that the assertions set in place in the <code>BaseObject</code> class will catch whatever the contract for toString() has been set up. Better even than that, the contract can be amended in <u>one place</u> and it will filter down throughout all subclasses. It&#8217;s OOP-DBC; and it could save your life &ndash; or at least your program.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.adventdigerati.com/2009/02/oop-dbc/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Future Proof</title>
		<link>http://blog.adventdigerati.com/2008/10/futureproof/</link>
		<comments>http://blog.adventdigerati.com/2008/10/futureproof/#comments</comments>
		<pubDate>Tue, 07 Oct 2008 05:18:40 +0000</pubDate>
		<dc:creator>Zack</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Code Snippet]]></category>

		<guid isPermaLink="false">http://adventtechnorati.wordpress.com/?p=8</guid>
		<description><![CDATA[Can we reference an algorithmically-named set of variables in one variable to make our PHP code as future proof as possible? Yes we can!]]></description>
			<content:encoded><![CDATA[<p>In every codebase you run into unique challenges. Space and time complexity are the enterprise programmer&#8217;s nemeses, and all too often appear as cousins to another problem: extensibility.</p>
<p>The problem with making anything a solitary factor more expandable is that it increases the complexity required to interface with that feature by at least twice that factor &mdash; twice in the sense that time and complexity, remember them?, are lower-bounded to being capable of handling the expansion.</p>
<p>Case in point: The difference between a pre-populated list and one whose values are variant depending on which portions of a codebase are considered &#8220;active.&#8221; This can pose quite the problem depending on how mission-critical this list is. (After all, this is a science; and all science should be repeatable <i>ad infinity</i>.) But how to retain this ability to accept a near-infinite range of values and manage them in some human-readable way?</p>
<p>Here we find the strengths and weaknesses of a language. In C, everything you touch is memory whether you realize it or not. From byte-pointers to malloc-ed blocks of hard disk, C keeps you up to your elbows in references. Perl scales the complexity back by a good factor, but grabbing references is still do-able: <code>$ref = \$scalar</code> is a direct accessor to the memory allocated by <code>$scalar</code>; and conversely, <code>$val = $$ref</code> gets the value of whatever variable resides at the memory location <code>$ref</code>. Pretty handy if you have an unknown-length set of variables with similar names. Now we have a common variable name we can manipulate without having a half-dozen Eval() functions in our code. (Aside: Eval() is nice, but sneakily evil; it&#8217;s slow, offers arbitrary code execution if use improperly, and just plain ugly.) Our syntax highlighters can show us exactly what we meant, and in six months when we&#8217;ll use this as the basis for the program&#8217;s next feature, we&#8217;ll have a much clearer idea of what the hell we wanted to get out of it.</p>
<p>But this is Perl. How do we do this in a language which masks references like PHP? Unfortunately, we can&#8217;t go flying around the memory stack as easily as Perl does, but we can get pretty close with a single Eval(). (Aside 2: I know, I just got done bashing Eval(); I haven&#8217;t forgotten, but we&#8217;re in control of the string this code evaluates, so take a breath.)</p>
<p>PHP offers an arguably more elegant Eval() than most languages, the <a href="http://www.google.com/codesearch?q=lang%3Aphp%20%22%24{%24%22&amp;btnG=Search+Code">inline eval</a>. So let&#8217;s reassume our situation: an unknown number of similarly-named variables is in our module&#8217;s scope and we want an elegant, memorable way to access their values for modulation.<br />
In Perl:</p>
<pre><code>$value_1 = "some important value";
for($i=1; $i &lt; $some_known_upper_bound; $i++) {
    $value_variable_name = "value_" . $i;
    $value = $$value_variable_name;
    # some modulator code
}</code></pre>
<p>In PHP:</p>
<pre><code>$value_1 = "some important value";
for($i = 1; $i &lt; $some_known_upper_bound; $i++) {
    $value_variable_name = "value_" . $i;
    # the magic...
    $value = ${$value_variable_name};
    # some modulator code
}</code></pre>
<p>And there you have it. Future proof code that modifies a like-named set of variables with a single, easily understood and aptly named variable.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.adventdigerati.com/2008/10/futureproof/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>
