Simple vs Flexible

simple-vs-flexibleSimple and Flexible does not always goes together. How do you choose between Simple vs Flexible ?

Let us take a very simple example. A string can be shown to the screen using two (or more) methods. We are going to use “Hello World” and two PHP code, echo and sprintf.

echo represents simple, because it functions only to output a string as is, while sprintf represents flexible, because it is very flexible in its usage. You can pretty much create anything and everything using sprintf. Within the scope of string manipulation, of course. 😉

I am linking the PHP Manual for echo and sprintf, so you can read before we continue, because I am going to reference to them in this article:

PHP: echo – Manual

PHP: sprintf – Manual

echo is very simple. You use it like this :

     echo "Hello World!";

You can add a variable to it, so it will retrieve the variable content and insert it to the string.

     $x = "World";
     echo "Hello $x !";
That's it, there is nothing else to it. It is simple as simple can get.

Look up the PHP manual for echo and you will see that the above is everything there is to echo.

sprintf on the other hand, is very flexible. You can rearrange the order of the variables, you can also specify the position of the variables.

Now, from the PHP Manual for sprintf, it is used like this:

$num = 5;
$location = 'tree';

$format = 'There are %d monkeys in the %s';
echo sprintf($format, $num, $location);

Note that sprintf works on formating a string. It can do a lot of wonderful thing on that string format.

%d means, the content is to be replaced with a decimal number.

%s means, the content is to be replaced with a string.

The function will search its list of arguments (variables) to match and replace the format.

You can, for example switch the argument around:

$format = 'The %s contains %d monkeys';
echo sprintf($format, $num, $location);

Note that we only changes the $format variables, while the sprintf statement and its variables remains the same.

Now, to the primary question. Which one do we use ?

Well, for me, simple first, so I use echo a lot. Why ?

Because flexible comes at a price. If you use a lot of sprintf or printf you will notice slower loading time. Flexible always comes at the price of speed.

So, the answer is, it depends. If you can take the speed penalty, then flexible is the way to go. Otherwise, go for simple.

Naturally, in real coding environment, things are different. Do you have experience ? Share with us in the comment section below.