LinuxGeex.Myhosting.Info: Do What I Mean - DWIM-ish Programming in PHP and Javascript
Articles Do What I Mean - DWIM-ish Programming in PHP and Javascript Feb 16th 2012

Programming in dynamic languages gives us flexibility which in turn provides us opportunities for rapid prototyping and often much faster development times as well.

With all this flexibility comes a cost in performance, and also often a cost in validating datatypes to ensure that we are doing sane things. There's not really any compiler to tell us not to pass an integer as an array, for instance. In the case of PHP it will typecast it to string and then to array, for example '$num=4096; echo $num[0];' will produce '4' as output, without any warning.

I am not going to propose solutions to this behaviour. In fact I'm going to suggest even more flexibility, but perhaps in the madness of that there will also be a measure of method. ;-)

Listing 1: (passing this a scalar as $data makes a mess!)

$template="Hello, %visitor%!\n"; $replace="%visitor%"; $data=array("World"); function foo($template,$replace,$data){ foreach ($data as $replacement){ $result[]=str_replace($replace,$replacement,$template); } return implode($result); } foo($template,$replace,$data); // Hello, World!\n foo($template,$replace,4096); // Hello, 4!\nHello, 0!\nHello, 9!\nHello, 6!\n

Listing 2: (tired of all that flexibility, let's enforce some restrictions!)

function foo($template,$replace,$data){ if (!is_array($data)){ user_error('foo: 3rd argument must be array'); return false; } foreach ($data as $replacement){ $result[]=str_replace($replace,$replacement,$template); } return implode($result); } foo($template,$replace,$data); // Hello, World!\n foo($template,$replace,4096); // false

Listing 3: ("Do What I Mean!" Is it madness? Let's make it more flexible:)

function foo($template,$replace,$data){ if (!is_array($data)) $data=array($data); foreach ($data as $replacement){ $result[]=str_replace($replace,$replacement,$template); } return implode($result); } foo($template,$replace,$data); // Hello, World!\n foo($template,$replace,4096); // Hello, 4096!\n

Here we have reduced the code complexity vs enforcing limitations, and in the process we have made this function more useful and we have solved the problem with the wrong datatype being passed in.

Powered by jEdit 4.3.2, the Programmer's Editor. Powered by SiteWrapper 1.0.1, the ultralight PHP CMS. Powered by LG Solutions, the web design professionals