Forum Moderators: coopster

Message Too Old, No Replies

Two questions about good programming practice

Omitting statement blocks and using variables as function names

         

maerk

11:40 pm on May 8, 2006 (gmt 0)

10+ Year Member



Is it good practice to omit statement blocks when they're unnecessary?

E.g.

if ($condition) echo $this;
else echo $that;

Also, is it OK to use variables in function names?

E.g.

if ($name=="cheese") {
$name(); // executes cheese()
} elseif ($name=="eggs") {
$name(); // executes eggs()
}

Thanks!

eelixduppy

11:52 pm on May 8, 2006 (gmt 0)



Hello...

If the statements aren't necessary than there is no need to include them. But i guess its a matter of preference and performance.

Apparently just like you can have variable variables, you can have variable functions as well... [us2.php.net...]

Something new learned every day :)

eelix

universetoday

3:36 am on May 9, 2006 (gmt 0)

10+ Year Member



This is kind of a defensive programming thing. Although it makes for shorter, cleaner code you can introduce bugs later on when you want to add another quick statement.

if (condition)
statement;
statement; // then you add this and the code breaks
else

So, if you never make a mistake, you're fine; otherwise you mind want to go with the blocks, no matter what, just to be safe.

grandpa

6:44 am on May 9, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Here's another vote for defensive coding.

Chances are pretty good that in any script that I write, I'll use the block form. If I switch to the unblocked form just because I can then I may end up with both types in the script. Someday I may have to troubleshoot that script.

In my opinion writing consistent code today will make any future work all that much easier. I use the block form in nearly every case, simply as a matter of consistency. In my shop thats a standard of good programming.

maerk

2:43 pm on May 9, 2006 (gmt 0)

10+ Year Member



Thanks everybody!

I only omit statement blocks rarely, usually to make the PHP shorter when it's a tiny bit inside an HTML tag. To me, it makes it more HTML-like; I hate it when there's a huge tangle of HTML and PHP, with snippets of HTML surrounding long bits of PHP, and then loads of echo statements scattered in the PHP -- makes it harder to write nice HTML. I guess I just plain don't like mixing the two unless I have to :D

<h1><?php if ($h1) echo $h1; else echo $title;?></h1>

This makes more sense to me.

As for the variable functions, well I'm glad they're there, and I discovered them completely by accident! (Which is why I was unsure about them.)