[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
|
$data = ''; //make sure it's set if (isset($_POST['name'])) { //make sure it's a string //trim whitespace $_POST['name'] = trim($_POST['name']); //make sure it contains content if (strlen($_POST['name']) > 0) { } else { $data = 'Error Occured'; } } else { $data = 'Error Occured'; } } else { $data = 'Error Occured'; }
Select what you want to copy and in doing so you will keep the formatting when pasting it.
|
|
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
|
function get_name() { //make sure it's set if (isset($_POST['name']) == false) { return 'Error
Occured'; } //make sure it's a string return 'Error
Occured'; } //trim whitespace $_POST['name'] = trim($_POST['name']); //make sure it contains content if (strlen($_POST['name']) == 0)
{ return 'Error
Occured'; } }
Select what you want to copy and in doing so you will keep the formatting when pasting it.
|
|
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. |
|
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.
|
|
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
|
|
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!!!!!!!
|
|
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.
|
|
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
|
|
Nice article. Good for beginners.
|
|
|
 |
Scott Thompson (24) United Kingdom, Lincolnshire |
|
VBAssassin has 32 fans
become a fan |
|
 |
|
 |
|