Coder Profile - Show off your skills, get a coder profile.
 
 
 
[PHP] - Lets kill the complex IF
Programming
Hi ya guys,

Have you ever nested that many if conditions that your code starts to get quite complicated? Let's give you an example
CODE: Copy / Restore  ::  Remove Scroll Bars
  1. $data = '';
  2.  
  3. //make sure it's set
  4. if (isset($_POST['name'])) {
  5.  
  6.        //make sure it's a string
  7.        if (is_string($_POST['name'])) {
  8.  
  9.               //trim whitespace
  10.               $_POST['name'] = trim($_POST['name']);
  11.  
  12.               //make sure it contains content
  13.               if (strlen($_POST['name']) > 0) {
  14.  
  15.                      $data = htmlentities($_POST['name'], ENT_QUOTES);
  16.  
  17.                      } else {
  18.                      $data = 'Error Occured';
  19.               }
  20.  
  21.               } else {
  22.               $data = 'Error Occured';
  23.        }
  24.  
  25.        } else {
  26.        $data = 'Error Occured';
  27. }
  28.  
  29. print $data;
Just some simple data checks on the $_POST['name'] value. But I'm not happy with that code. For something so simply, why is the code so complex? Let's use a technique with functions to make this much simpler. Then explain how it works in regards to simplifying it.
CODE: Copy / Restore  ::  Remove Scroll Bars
  1. function get_name() {
  2.  
  3.        //make sure it's set
  4.        if (isset($_POST['name']) == false) {
  5.               return 'Error Occured';
  6.        }
  7.  
  8.        //make sure it's a string
  9.        if (is_string($_POST['name']) == false) {
  10.               return 'Error Occured';
  11.        }
  12.  
  13.        //trim whitespace
  14.        $_POST['name'] = trim($_POST['name']);
  15.  
  16.        //make sure it contains content
  17.        if (strlen($_POST['name']) == 0) {
  18.               return 'Error Occured';
  19.        }
  20.  
  21.        return htmlentities($_POST['name'], ENT_QUOTES);
  22.  
  23. }
  24.  
  25. print get_name();
So, why is this code simpler? First of all, look at the indenting and nesting. Indenting is at a maximum level of just 2 tabs and nested ifs, well, there aren't any! Due to there being no nested ifs there is no reason to get the closing braces confused or have to take else statements in to account. Imagine how complicated things would get if there were 30 nested ifs! Execution flow is also much easier to follow because one if condition is executed, and then totally forgotten about (unlike nested conditions).

There is also the added encapsulation that the function provides (protection from the code outside of the function) which is always a plus.

That's all on this subject for now.

Kind regards,
Scott

P.S. I have not run this code for errors however, the purpose is to show you the difference in the look of the code so it shouldn't matter if the code has a few syntax errors. I could have written it in pseudo code and it wouldn't have made a difference.
Please login to rate coding articles.

Click here to register a free account with us.
Comments
Please login to post comments.
 
Uranium-239     Posted 2.65 Years Ago
 
 
Dude, its not about printing, the 80 char rule has been around long before the
integrated developing environment was invented - I fail to understrand why you find
that funny? I am right, it is to accomadate command line interfaces which generally
follow dimensions of 80x25.

And @ your preferred coding style - You can probably get away with it more in PHP -
But I hope you wouldn't dream of doing it in a programming language.

There are a few instances where it is acceptable but generally it results in
repeated code which is bloated, unnecessary and slow. All for what? Coding Style?

Whilst you probably won't notice a speed difference with the kind of stuff you
write, if you are writing code that is constantly being executed in a short space of
time then you will notice a big difference in speed. I remember once I was building
the graphical user interface for an operating system I was working on and its amazing
how reworking your code and optimizing in such a way as demonstrated can have a big
effect on performance.
 
VBAssassin     Posted 2.65 Years Ago
 
 
Actually Uranium, 80 chrs per line is actually down to PRINTING lmao. Since if you
print off your source code the last thing you want is for it to wrap... and 80 was
chosen ;-) Or at least thats why recent IDE's such as Delphi show you an
indication at 80 chrs plus it prevents you have to scroll horizontally and vertically
;-)

Also, in regards to:
--------
if(!(var1 = func(bleh)))
return;

if(!(var2 = func(var1)))
return;

if(!(var3 = func(var2)))
return;

// code here
---------

I love that coding style for functions/methods... you dont have to waist your time
reading code thats not relevant anymore (because the function has done its job) and
it makes debugging nice and easy. My thumbnail class for this site uses it, as well
as the bbcode class... eg:

//md5 bbcode

//if cached version, return that
if () {
return $cached;
}

//no cache hit, so parse bbcode

//bla bla bla

MUCH better than following up and down conditional statements. Doesn't matter
what you say to try and convince me otherwise... i've tried and tested it many
times.

kind regards,
Scott
 
Uranium-239     Posted 2.65 Years Ago
 
 
Write, ima make this as short as possible.

Craige: the 80 chars per line rule doesn't originate from 800x600 screen
resolutions. It is there because the standard settings for text modes - your computer
is first booted up in this mode and I think the command prompt and terminal still run
in this mode - are 80x25.

Visie: Your code example is poor - you would be much better off following the
standard coding style instead of putting your own twist on things - they exist for a
reason and have been developed over many years of experience.

First off, this applies to VBAssasin aswell, your first two if statements could
easily be merged into one, as a rule, if the consequence of two if statements is the
same - they should be bound into one. The logical or operation exists for a reason :p

Secondly, Visie, your code will continue to perform functions on the variable $n
after you have discovered it to be invalid!!!! You could end up performing the strlen
and trim functions on a variable which isn't set or isn't even a string.

Thirdly, why in God's name did you call the variable 'n'? I really
would like to know. It tells you nothing about what the variable 'n'
actually contanis - and as 'n' and 'i' are common variable names
for integers - you almost certainly should not use it!!! 'e' is also a
stupid name for a variable.

Generally, you shouldnt sacrifice execution flow for coding style aswell.

--------
if((var1 = func(bleh))) {
if((var2 = func(var1))) {
if((var3 = func(var2))) {
// code here
}
}
}
--------

Is much better than:

--------
if(!(var1 = func(bleh)))
return;

if(!(var2 = func(var1)))
return;

if(!(var3 = func(var2)))
return;

// code here
---------

It will execute much quicker, and, if dealing with a compiled language, it will
compile into a shorter set of instructions - because you won't have to repeat
the exit statement 3 times!!!!!!!
 
Craige     Posted 2.82 Years Ago
 
 
As a rule, your code should not cross over the 80th column. While this is generally
held over from the days of 800*600 resolutions, realistically anything longer than 80
characters can and should be simplified. If you hit 81 characters on a line, you need
to rethink your application logic/formatting.
 
Visie     Posted 2.82 Years Ago
 
 
For a clearity, I use the clampfree-syntax, the screamer for booleans, short vars and
expressions (very usefull) :)

function get_name($min_length) {

$n = $_POST['name'];

// make sure it's set
if (!isset($n)) $e[] = 'Error Occured';

//make sure it's a string
if (!is_string($n)) $e[] = 'Error Occured';

//trim whitespace
$n = trim($n);

//make sure it contains content
if (strlen($n) < $min_length) $e[] = 'Error Occured';;

// return error-array or data
$return = is_array($e) ? $e : htmlentities($n, ENT_QUOTES);

return $return

}

print get_name(4);

Your third check is imho futile if you compare a 0-char-length, 'cause an
empty string (check 2), isn't a string... it's null. I think so... Oo
 
Izzmo     Posted 2.95 Years Ago
 
 
Nice article. Good for beginners.
Page 1 of 1
More Articles By This Author
[PHP] - Lets kill the complex IF
How to use Memcache on Windows
PHP Sessions = Member Database Cache
Speed Up Delivery of your JavaScript Libraries
AJAX - When to use it?
Null Byte Poison - How it works...
Versioning Your Application
Preventing raw PHP leaks on Apache
All VB6 Global Functions & Objects
ASCII List
Scott Thompson (24)
United Kingdom, Lincolnshire
VBAssassin has 32 fans
become a fan
� Applications
Articles Articles (13)
Source Codes Source Codes (61)
� About Me
About Me About Me
User Groups User Groups (9)
Portfolio Portfolio (8)
Friends Friends (178)
� Misc
Overview Overview
Send A Friend Invite
Send Message Send A Message
RSS Whole Profile Feed
 
 
Latest News About Coder Profile
Coder Profile Poll
Why do you get bored with programming?

Not enough time to do something productive
I run out of ideas
Too hard to show people my creations
Everything i do has too many errors, and it's too hard
I don't get bored!!!


please login to cast your vote
and see the results of this poll
Latest Coder Profile Changes
Coder Profile was last updated
2.96 Years Ago
Official Blog :: Make A Donation :: Credits :: Contact Me
Terms & Conditions :: Privacy Policy :: Documents :: Wallpapers
Version 1.46.00
Copyright � 2007 - 2011, Scott Thompson, All Rights Reserved