Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 7 of 7
  1. #1
    Master Coder
    Join Date
    Feb 2011
    Location
    Your Monitor
    Posts
    5,099
    Thanks
    109
    Thanked 602 Times in 589 Posts

    TIP: Coding styles and $end errors

    Hi

    I'm sure many of you have come across the "Unexpected $end" or "Missing $end" messages many times and it's probably taken you many minutes, hours or even days to find it. If its the latter two options i'm sure if you're like me it's probably taken you a lot of desk thumping to to identify the fault.

    Firstly I'd like to show you two different coding styles here:
    PHP Code:
    <?
    //Example A - The most popular
    function test_a($Input){
    if (
    $Input){
    print 
    'a';
    }
    }

    //Example B - Less popular
    function test_b($Input)
       {
       if (
    $Input)
          {
          print 
    'b';
          }
       }
    ?>
    I've personally always found example B not only clearer to understand but easier to debug. Despite not fitting with the 'peer pressure' from other coders it is actually a lot nicer to work with and Notepad++ demonstrates this nicely too:



    If you look at example A, you'll see that the opening brace is highlighted red along with its partner - Great huh?

    Look at example B though and you'll see why it's so much easier to debug. Not only are the opening and closing braces highlighted red, NP++ also draws a red dotted line down the page directly to it so you can see it (Apologies, Photoshop didn't preserve the red dotted line very well). If you indent each block of braces as I have then it only makes things far easier to debug.

    Following a recent thread by a member today I thought I would post this thread with a practical example in the hope that it helps others out here. The code has been slightly modified to remove the non-necessary html but it still serves as a good example for this demonstration:

    PHP Code:
    <?php
    //This code will generate a missing $end error message
    session_start();
    require 
    'database.php';
    $nuser=$_SESSION['user'];
    $auser=$_SESSION['admin'];

    if(
    $nuser){
    $userfinal=$nuser;
    }elseif(
    $auser){
    $userfinal=$auser;
    }
    if(isset(
    $userfinal)){
    $Members mysql_query("SELECT user FROM characters WHERE level ='1' ORDER BY exp DESC") or die(mysql_error());
    $numRowsMembers mysql_num_rows($Members);

    for(
    $count 1$count <= $numRowsMembers$count++){
    $name mysql_fetch_array($Members);

    echo 
    "<a href=\"member_profile.php?username=$name[user]\"> $name[user]</a></td>";
    }
    ?>
    Now I'd like to show you this at work in Notepad++:
    Style A:


    Notice how the opening { are paired with the closing } in red circled with matching colours. The single { by itself is circled in red. Ok, by pointing at each opening { I've found the { without its partner - but where should I now put the closing } ?

    The answer lies in Style B - using indentations and brackets on their own lines. Take a look at this:


    Again, you can see all the correctly paired opening { and closing } in red circled with matching colours with the odd { circled in red.

    Now due to the original authors code, there is no way of knowing if that for() block was supposed to be inside that block or outside of it. For demonstration purposes only, I'm going to show you what would of happened if it was supposed to be inside:


    Did you notice that red dotted line circled in blue? - It shows you exactly where the closing } should be.

    Now, lets look at the finished code:


    Done, with ease. No time wasted, no head scratching, no convincing yourself there is no error with the code and the computer is wrong etc.

    I hope that by posting this topic, some of you will see tha advantages that Style B has when used with a proper editor like Notepad++ and that it can actually help you to fix code rather than make it difficult like style A.
    Last edited by tangoforce; 05-10-2011 at 01:00 PM.
    Quote Originally Posted by deathshadow View Post
    So seriously, loosen up that tie, let out the belt, and try relating to normal people on the street instead of the gentleman's club crowd.

  2. #2
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    17,026
    Thanks
    4
    Thanked 2,668 Times in 2,637 Posts
    I'm quite a fan of this style with a minor variation: I set each brace aligned with the branch or control, and indent only where we exceed 80 chars on a line:
    Code:
    public int myMethod(<T extends Number> myIn)
            throws InvalidArgumentException
    {  
    }
    for example.
    I have NEVER been a fan of the braced single line, as its particularly difficult to identify braced and non-braced control blocks:
    Code:
    int c = 0;
    for (int i = 0; i < 10; ++i)
        ++c;
    
    // compared to
    int c = 0;
    for (int i = 0; i < 10; ++i) {
        ++c;

    The only thing to note, is that many employers do have a particular code format style. So you must adhere to these styles. Fortunately, IDE's such as eclipse allow you to design multiple code templates, so when you are done with how you like to do it, you can apply a work style to reformat it if it uses the more common format.

    This thread also deserves to be added to the PHP Frequenly Asked Questions thread.

    Edit:
    Sorry, can't quite recall the java syntax there for the exception. Its either InvalidArgumentException or IllegalArgumentException, but we shouldn't really get either in any case, it was just to show the indenting
    Last edited by Fou-Lu; 05-10-2011 at 03:49 PM.

  3. #3
    UE Antagonizer Fumigator's Avatar
    Join Date
    Dec 2005
    Location
    Utah, USA, Northwestern hemisphere, Earth, Solar System, Milky Way Galaxy, Alpha Quadrant
    Posts
    7,692
    Thanks
    42
    Thanked 637 Times in 625 Posts
    Nice job on your tip. I used to use the first style but when I first started using CodeIgniter I switched to the second style. Mine's a bit different from yours-- I adopted CodeIgniter's style completely so my brackets are set on the same indent as the block identifier and all code inside the block is on its own indent. Notepad++ draws nice little dotted lines giving it a clean look.


  4. #4
    Master Coder
    Join Date
    Feb 2011
    Location
    Your Monitor
    Posts
    5,099
    Thanks
    109
    Thanked 602 Times in 589 Posts
    Hi guys

    Yeah I generally see the following two styles as being the same thing:
    PHP Code:
    function test_b()
        {

        }

    function 
    testb()
    {


    I know it is technically different but the braces are still on their own lines so i see it as the same thing. I've always found it easier to understand though if they're indented from the function / class delcaration. I've never liked style A as its just too hard to understand, debug and most of all deal with $end errors. I have no idea what anyone likes about that style and why so many people use it. I can work with it, but i always end up copying the code from one notepad++ tab to another, formatting it my way, working on it, formatting it back and then pasting it back in.

    Hopefully the screen shots in this thread will enlighten others
    Quote Originally Posted by deathshadow View Post
    So seriously, loosen up that tie, let out the belt, and try relating to normal people on the street instead of the gentleman's club crowd.

  5. #5
    Regular Coder
    Join Date
    Jan 2017
    Posts
    187
    Thanks
    18
    Thanked 0 Times in 0 Posts

    Cool

    I am a complete newbie in php and while using notepad++, I realized coding the type A way looked messy and so without any tutor's or any expert's help, I started making my own style which I see now you call style b. Actually, my style is abit more INDENTING and so you can call it style c if you like.
    I do it like this ...

    PHP Code:
    if
    {
        echo 
    "blah";
        if
        {
            echo 
    "blah";
        }
        else
        {
            echo 
    "blah";
        }
    }
    else
    {
        echo 
    "blah";

    Just look how easily you can spot the paired closing bracket for each condition.
    I hope my style would become handy for you.
    It is amazing is it not when you start building your own style while learning and find others more experience are thinking and doing things along the same line ? Nay! It feels better when you've built a system after starting on a subject for 2wks and your system proves to be better than what all the oldbies and experienced people use and are still using! (No offense but: chuckle!)
    Last edited by UI Man; 03-17-2017 at 10:53 PM.

  6. #6
    Senior Coder benanamen's Avatar
    Join Date
    Oct 2015
    Posts
    1,145
    Thanks
    2
    Thanked 118 Times in 115 Posts
    It's generally considered bad forum etiquette to resurrect threads that are 6 years old.

    There are standards with actual names besides a and b. The Only Correct Indent Style | Terminally Incoherent
    To save time, lets just assume I am almost never wrong.

    The XY Problem
    The XY problem is asking about your attempted solution (X) rather than your actual problem (Y). This leads to enormous amounts of wasted time and energy, both on the part of people asking for help, and on the part of those providing help.

    "This text has been encoded with ROT26. If you can read this you must have found a backdoor. Congratulations!"

  7. #7
    Master Coder
    Join Date
    Feb 2011
    Location
    Your Monitor
    Posts
    5,099
    Thanks
    109
    Thanked 602 Times in 589 Posts
    Quote Originally Posted by UI Man View Post
    Just look how easily you can spot the paired closing bracket for each condition.
    Yet you could not find your missing } in the other topic? Now you've also developed your own coding style to share with the world?

    Look, I appreciate you want to play with other programmers but you are trying to get way ahead of yourself before you really even understand many basics. You didn't develop that style, Yes you've stumbled on it lol but you didn't develop something when it already existed. My A and B styles that I posted were purely as an example. There are all sorts of other ways to indent the code and put opening and closing parts.

    Quote Originally Posted by UI Man View Post
    It feels better when you've built a system after starting on a subject for 2wks and your system proves to be better than what all the oldbies and experienced people use and are still using! (No offense but: chuckle!)
    With respect, several of us have pointed out some problems with your code relating to security and your usage of sql. You don't seem bothered by this. Your system is not better than what more experienced people are using. It is insecure and likely to be hacked.

    benanamen, 6 years of not, resurrecting any thread is an option open to any member of this forum. Threads are not time locked. If someone wants to resurrect one of my topics for whatever reason they are welcome to.

    Interesting link though.. thanks for that
    Last edited by tangoforce; 03-18-2017 at 01:00 AM.
    Quote Originally Posted by deathshadow View Post
    So seriously, loosen up that tie, let out the belt, and try relating to normal people on the street instead of the gentleman's club crowd.


 

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •