Welcome Guest, Not a member yet? Register   Sign In
I find myself creating groups of code, is this wrong?
#1

[eluser]TornUp[/eluser]
hi all,

Not been on here in a long time..

My question is... i find myself developping in a very blocky way, and don't seem to be a big fan of nesting IF/Else into each other..

for example.

Code:
If ($this->check_username($username) === TRUE AND $this->check_email($email) === TRUE){
$final_checks = TRUE;
}
else{
$final_checks = FALSE;
}

if ($final_checks === TRUE AND $somthing_else === TRUE AND $so_on === TRUE )
{
Insert into the DB
}

or should i just break my habit and start nesting If/Else statements?

I thought it best to ask before i get to a stage where i would have to rework alot of my code..

Thanks
#2

[eluser]WanWizard[/eluser]
I'm afraid there isn't a definite answer to this question, other than 'it depends'.

I usually nest my IF's (I don't like to introduce extra complexity by using control flags), and split code into different methods where handy and appropriate.
#3

[eluser]nzmike[/eluser]
Personally I find nested if statements easier to read and understand. When I read code like that I have to keep track of the flag variables and which if statement they came from. On the other hand, with nested if statements I know exactly where I am and what conditions are required in execution to get to that point.
#4

[eluser]TornUp[/eluser]
i find code easyer to read with the way i do it, i just don't want to impact on proformance!?

so there isn't a case where i MUST nest if's?

many thanks for your reply, and thanks in advanced for any fiture replys Smile
#5

[eluser]jedd[/eluser]
[quote author="TornUp" date="1252855261"]
so there isn't a case where i MUST nest if's?
[/quote]

With PHP it's rare that you MUST do anything in any particular manner.

I can't see how this isn't more readable than setting up several additional variables and tracking their status:
Code:
/// If the user's already logged in, offer them a choice:
if ($current_handle = $this->session->userdata('handle'))  {
    // This is where we test if we're on a redirect() - so show top-bar-div username.
    if ($this->session->flashdata("just_logged_in") )  {
        if ($this->session->flashdata('return_to_page'))
            redirect ($this->session->flashdata('return_to_page'));
        else
            $this->data['main_content_view']  = "Welcome back, <b>". $current_handle ."</b>";
        }
    else
            ...

I've read that switches are much faster than a string of ifs, but it's often convoluted to adjust your logic and variables to suit a switch construct.

I'd suggest that if you're sticking with your approach that you adopt some standard for identifying your highly ephemeral flag variables, so they are readily identifiable.

My gut feel is that if your biggest performance concern is nested rather than consecutive strings of if/else blocks .. you're in an enviable situation.
#6

[eluser]nzmike[/eluser]
jedd is correct, you should be worried about the overall performance of the algorithms in your program rather than individual if statements.

Have a look at "Big O notation" so you can get a feel for how fast an algorithm is in your program. Here's the wikipedia article on it - http://en.wikipedia.org/wiki/Big_O_notation
#7

[eluser]wiredesignz[/eluser]
@nzmike, It might help if you took the time to explain what "Big O notation" is and how it applies here, maybe give some examples. Thanks.
#8

[eluser]nzmike[/eluser]
Good point, the wikipedia article is a little technical.

Ok so here's a quick explanation off the top of my head. Any of you theory geeks out there, feel free to correct me if something is wrong. I should really emphasis this is a really brief watered down explanation. There's plenty of websites out there providing an in-depth explanation.

Measuring the time a piece of code takes in milliseconds isn't particularly useful. There are so many different factors (CPU speed, the language you're using, how many other processes are running, etc.) that is doesn't give us a true idea of how fast an algorithm is.

Big O notation takes a more abstract view and measures an algorithm's speed in terms of the number of items (n). This measurement is the worst case for the algorithm as it is the only thing we can guarantee.

Here are the most common Big O Notations and an example of a algorithm with that time complexity.My apologies if you don't understand some of the algorithms, some of the time complexities are hard to think of algorithms related to web development.



O(1) (constant)

1. Calculating a hash for a given entry in a hash table.

Calculating a hash will always take the same amount of time no matter how big a hash table is.

2. Possibly calculating the length of an array. (I'm not actually sure how PHP stores array lengths but I would assume it takes the same amount of time no matter the size of the array).

Code:
count(my_array)


O(log n)

1. Traversing a balanced tree

Code:
O
      / \
     O   O
    / \ / \
   O   OO  O

You can guarantee at worst case it will take log n steps to reach any node in this tree (n is the size of the whole tree)

2. A PHP version of a O(log n) algorithm would look something like this:

Code:
for(i = 10000; i > 1; i = floor(i/2.0)) {
   echo i;
}

Notice how 'i' is cut in half each iteration.


O(n)

1. Where you look at each element in an array

Code:
for(i = 0; i < count(my_array); i++) {
    echo i;
}


O(n log n)

1.Merge sort (One of the fastest sorting algorithms)

Here's the wiki page - Merge Sort


O(n^2) - Insertion sort (Slowish sorting algorithm)

1. Most people would sort a pack of cards using this algorithm

Wiki page - Insertion Sort

2.or some PHP code:
Code:
for(i = 0; i < count(my_array); i++) {
   for(j = 0; j < count(my_array); j++) {
       echo i + j;
   }
}


O(n!)

1. Finding every variation of a given set.
Code:
{1,2,3}
{1,3,2}
{2,1,3}
{2,3,1}
{3,2,1}
{3,1,2}

As you can probably tell Big O is more about the scalibity of an algorithm rather than the physical time taken. A O(1) algorithm could easily be slower than an n! when measured in microseconds, however you would probably want to use the O(1) algorithm.


Imagine I have an array of 2 numbers and 2 algorithms one of time complexity O(n) and the other of time complexity O(n!) which both essentially do the same thing except they use different algorithms.

I call the first function (The O(n) one),give it the array and it takes 200 microseconds. I then call the second function (The O(n!) one), give it the array and it takes 20 microseconds. So the O(n!) algorithm must be faster right?

What would happen if I increased my array to 100 numbers. The first algorithm might take around 20000 microseconds but the n! would take more time than has passed in the universe!

I guess my overall point is don't get caught up on whether echo is faster the print or if you should use nested if statements or have flag variables. If you're concerned about performance, look at the time complexity of the algorithms in your program.

I'm bound to have got something wrong as I wrote this without using any notes but hopefully you get the overall concept.

[/mammoth_post]
#9

[eluser]BrianDHall[/eluser]
As far as performance worries, lets say somehow it cost an extra 10,000 clock cycles (I can't imagine how it could possibly take that much extra), and you had 10 accesses every second (that would mean 25 million hits a month, in which case I congratulate you on your newfound millions), that means your 'inefficient' coding would cost you 100,000 clock cycles.

The AMD Athlon, which hit the market in approximately 2000 (nearly 10 years ago) gets nearly 3,000,000 instructions per second. So your 'inefficient' coding might cost you 1 tenth of 1 second of processor time if you had a site getting over 20 million hits a month. Of course, modern processors can now easily obtain over 20,000,000 instructions per second.

In short: don't worry about it. Big Grin

As to is it a 'bad' thing, I've wondered this myself. Sometimes I want something simple like "if logged in, show the page", and it just seems untidy to indent all but like 5 lines of my code inside an if/else wrapper just because of that.

The thing is, for basic structure there is only two options - nest or use 'flags' as you do. One is not necessarily better than another, so you aren't really doing anything wrong.

To get a real improvement you have to move outside of the structure being used and handle control at an earlier point. For instance, check to see if someone is validated in a MY_Controller or Constructor, and if not then prevent the program from ever reaching the function that requires a person to be validated to start with.

By moving these checks outside your present function and to elsewhere in your program, then and only then can you see a real improvement in simplified programming and not need either nested if statements or control flags. However, the downside is that you increase the scope of the program that must be known to understand how it works - to be sure your function is secure you have to be aware of what is going on in a parent class, constructor, etc. Here, it depends on your program as to whether or not this is an improvement or an unnecessary increase in complexity.
#10

[eluser]jedd[/eluser]
[quote author="BrianDHall" date="1252954582"]
... which hit the market in approximately 2009 (nearly 10 years ago) ..
[/quote]

I get accused of living in the past all the time, but I didn't realise I'd let things slide quite that badly.




Theme © iAndrew 2016 - Forum software by © MyBB