1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

What is the best code writing practice?

Discussion in 'Programming' started by nekowai, Apr 24, 2017.

  1. #1
    <img src="<?php echo $image_url; ?>">
    PHP:
    OR

    echo '<img src="'.$image_url.'">';
    PHP:
    OR

    echo "<img src=\"{$image_url}\">";
    PHP:

     
    nekowai, Apr 24, 2017 IP
  2. akhileshbc

    akhileshbc Active Member

    Messages:
    98
    Likes Received:
    1
    Best Answers:
    5
    Trophy Points:
    75
    #2
    I would prefer the first choice!
     
    akhileshbc, Apr 25, 2017 IP
  3. PoPSiCLe

    PoPSiCLe Illustrious Member

    Messages:
    4,623
    Likes Received:
    725
    Best Answers:
    152
    Trophy Points:
    470
    #3
    The second one would be the recommended one, except with , (comma) as concating delimiter, instead of . (period). So this:
    
    echo '<img src="',$image_url,'">';
    
    PHP:
    The others are not recommended - the first one you should always avoid. There should only be one <?php on the page. Do not repeat the start / ending of PHP-tags.
    The third one is messy, and you will get tired very quickly writing the escaped double quotes. Use single quotes around strings, and use concatination, instead of auto-parsing of variables inside double-quoted strings.
     
    PoPSiCLe, Apr 25, 2017 IP
    qwikad.com likes this.
  4. nekowai

    nekowai Well-Known Member

    Messages:
    256
    Likes Received:
    6
    Best Answers:
    0
    Trophy Points:
    130
    #4
    Does the comma has any advantage to the period?
     
    nekowai, Apr 25, 2017 IP
  5. nekowai

    nekowai Well-Known Member

    Messages:
    256
    Likes Received:
    6
    Best Answers:
    0
    Trophy Points:
    130
    #5
    It's explained on echo's syntax:
    void echo ( string $arg1 [, string $... ] )
    PHP:
     
    nekowai, Apr 25, 2017 IP
  6. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,998
    Best Answers:
    253
    Trophy Points:
    515
    #6
    Executes faster, and in the order you would think it would.

    Periods mean string addition -- the values you pass have to be added together first. That means memory has to be allocated for the result, a string addition has to be performed into the new memory, the pointer to that new memory sent to echo, and then the memory de-allocated/recycled (aka garbage collection) after.

    If you comma delimit parameters with echo, each one's pointer is passed in turn, using no extra memory apart from the size of each pointer. It's just faster as no addition/copy of the values is needed, the original 'pieces' are just used as is.

    Double-quoted like the last one in your first post is even worse, as then PHP has to parse the string turning it into an echo, making it take even longer and possibly use even MORE memory.

    You also have the execution order issue.... get a load of this:

    
    function test() { echo 'test'; }
    echo 'this is a ' . test() .'<br>';
    echo 'this is a ', test(), '<br>';
    
    Code (markup):
    The output from that?

    
    testthis is a
    this is a test
    
    Code (markup):
    For the string addition to take place, the function has to be run FIRST, meaning that the echo inside test() runs BEFORE the echo that's calling it. Comma delimited values are passed in turn, meaning that the execution order you would expect is implemented.

    ... also, 90%+ of the time, stick with single quote strings. They're just less headaches -- I only use doubles when I NEED escape codes that don't work in single quote strings. They are inherently slower since they have to look for more possible escape codes, embedded variables, and so forth. Same reason few if any sane PHP developers use printf.

    MIND YOU, head to head singles vs. doubles the difference is about 5% maximum JUST for the operation, and maybe less than half a percent in a real-world program, but when it's the difference between hitting shift and not hitting shift, use the more efficient one from the start! ESPECIALLY when you're outputting something like HTML where double quoters are supposed to be used with singles being the fallback, not the norm.

    Generally speaking, I see single quotes in HTML output by PHP, I automatically assume the person writing PHP wasn't qualified to do so.
     
    deathshadow, Apr 26, 2017 IP
    PoPSiCLe likes this.
  7. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,998
    Best Answers:
    253
    Trophy Points:
    515
    #7
    Oh and if you're going to do the halfwit "open and close PHP all over the damned place" rubbish, learn about the echo shorttag if all you are going to do is echo.

    
    <?= $test ?>
    <?php echo $test; ?>
    
    Code (markup):
    Both lines are functionally identical. As of any MODERN PHP implementation (5.4+) , <?= is enabled by default all the time -- it used to be disabled by default along with using <? instead of <?php, but they relized that disabling both was stupid given that <?= would NOT conflict with... whatever the hell it was they were worried about conflicting with that no sane developer used in the first damned place... I don't even remember what it was they were worried about with that...

    Oh, that's right, they were worried about some EDITORS failing to syntax highlight (something I don't even use) XML due to a conflict between <? and <?xml -- something <?= does NOT conflict with in most cases... NOT that we dick around with XML prologues or syntax anymore in proper web development...

    So yeah, <?=, IF you're going to use that rubbish, keep it in mind.
     
    deathshadow, Apr 27, 2017 IP
  8. NetStar

    NetStar Notable Member

    Messages:
    2,471
    Likes Received:
    541
    Best Answers:
    21
    Trophy Points:
    245
    #8
    Something tells me his entire script will be a mix of HTML and PHP... the best option is to separate programming from presentation...
     
    NetStar, May 12, 2017 IP
  9. alfredopacino

    alfredopacino Peon

    Messages:
    2
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    1
    #9
    maybe not the best way to introduce myself :D, but I would point out the difference in terms of performance between comma and point is pretty irrelevant in real world usage. Even compared with double quote interpolation, the slowest method of the list.
    If you concatenate 1 million of string then yes, you would note the difference.
     
    alfredopacino, Jun 3, 2017 IP
  10. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,998
    Best Answers:
    253
    Trophy Points:
    515
    #10
    You mean like if you do it fifty times in a single file spread out over 20K server requests?
     
    deathshadow, Jun 4, 2017 IP
    PoPSiCLe likes this.
  11. outofbandii

    outofbandii Active Member

    Messages:
    19
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    86
    #11
    Reminds me of something I once wrote

    
    <form method="post" action="<?php the_permalink(); ?>">
        <table><tbody><tr>
            <?php
                $current_user = wp_get_current_user();
                $user_video_pref = get_user_meta($current_user->ID, 'namespace_video_size_pref', true);
                $arr = array("960x540","720x406","320x180", "Auto");
                echo "\n";
                foreach ($arr as $value) {
                    echo "\n<td id='td-".$value;
                    echo "' onMouseOver=\"this.style.backgroundColor='#f9f9f9'\"; ";
                    echo "  onMouseOut=\"this.style.backgroundColor='#DCDCDC'; if (document.getElementById('namespace_video_size_pref".$value."').checked) {document.getElementById('td-960x540').style.backgroundColor='#DCDCDC';document.getElementById('td-720x406').style.backgroundColor='#DCDCDC';document.getElementById('td-320x180').style.backgroundColor='#DCDCDC';document.getElementById('td-Auto').style.backgroundColor='#DCDCDC';this.style.backgroundColor='#f9f9f9'; }\" ";
                    echo "  onClick=\"this.style.backgroundColor='#DCDCDC'; if (document.getElementById('namespace_video_size_pref".$value."').checked) {document.getElementById('td-960x540').style.backgroundColor='#DCDCDC';document.getElementById('td-720x406').style.backgroundColor='#DCDCDC';document.getElementById('td-320x180').style.backgroundColor='#DCDCDC';document.getElementById('td-Auto').style.backgroundColor='#DCDCDC';this.style.backgroundColor='#f9f9f9'; }\" ";
                    echo " style='padding:0; border:0;";
                    if ($value==$user_video_pref) echo " background-color:#f9f9f9; border: 2px solid #444' class='namespace-selected-video-option";
                    echo "'>\n<label for='namespace_video_size_pref".$value."'>";
    
                    if ($value=="960x540")     echo "<h3 style='margin:0 0 0 45px;'>Large</h3>";
                    if ($value=="720x406")     echo "<h3 style='margin:0 0 0 45px;'>Medium</h3>";
                    if ($value=="320x180")     echo "<h3 style='margin:0 0 0 45px;'>Small</h3>";
                    if ($value=="Auto")     echo "<h3 style='margin:0 0 0 45px;'>Auto</h3>";
    
                    echo '<img src="http://images.namespace.com/';
                    echo $value.'.gif" alt="Choose image size" style="border:1px solid #585F6B;" /> <br/>';
                    echo '<input type="radio" style="padding:10px; margin: 5px 0 0 70px " name="namespace_video_size_pref" id="namespace_video_size_pref'.$value.'" value="'.$value.'"';
                    if ($value==$user_video_pref) echo " checked ";
                    echo "><br />&nbsp; <br /></label>";
                    echo "\n</td>\n";
                }
            ?>
        </tr></tbody></table>
        <input name="updateuser" type="submit" id="updateuser" class="submit button" value="Update" />
        <input name="action" type="hidden" id="action" value="update-user" />
    </form>
    
    Code (markup):
    All I can say about it is that it worked. And I'm sorry.
     
    outofbandii, Jun 29, 2017 IP
  12. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,998
    Best Answers:
    253
    Trophy Points:
    515
    #12
    |
    Heh, when I say "laundry list of how NOT to write a website"?!? -- there's a GREAT example, it's got a little of everything.
     
    deathshadow, Jun 30, 2017 IP
  13. outofbandii

    outofbandii Active Member

    Messages:
    19
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    86
    #13
    F**k it, it worked. If the project was a huge success I'd happily have refactored it to something a bit less cringeworthy :)
     
    outofbandii, Jun 30, 2017 IP
  14. NetStar

    NetStar Notable Member

    Messages:
    2,471
    Likes Received:
    541
    Best Answers:
    21
    Trophy Points:
    245
    #14
    Honestly.. the refactoring isn't so it's less cringeworthy and worthy of praise by a programmer... it's so it's easier to extend, debug, and develop from... I wrote cringeworthy code at one time and once the project got BIG it became near impossible to extend...
     
    NetStar, Jul 3, 2017 IP
  15. outofbandii

    outofbandii Active Member

    Messages:
    19
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    86
    #15
    I agree. But hacks have their place when extending, debugging and development are not going to happen. And unfortunately in this case the project died with very few users ever running that code, so refactoring never became necessary :(
     
    outofbandii, Jul 3, 2017 IP
  16. NetStar

    NetStar Notable Member

    Messages:
    2,471
    Likes Received:
    541
    Best Answers:
    21
    Trophy Points:
    245
    #16
    I disagree. Hacks have their place? That is setting yourself up for failure. It's takes the same amount of effort to write good clean code using proven design patterns that allow you to easily extend your code. When you mix presentation and application logic code your project becomes very complex to edit. And if you aren't designing using some sort of foundation or structure then it becomes extremely difficult to grow. If you're working on a dead project with no future why are you even bothering?
     
    NetStar, Jul 3, 2017 IP
  17. outofbandii

    outofbandii Active Member

    Messages:
    19
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    86
    #17
    The project wasn't dead when I wrote that.

    And hacks most certainly do have their place.

    I think we'll agree to disagree.
     
    outofbandii, Jul 4, 2017 IP
  18. NetStar

    NetStar Notable Member

    Messages:
    2,471
    Likes Received:
    541
    Best Answers:
    21
    Trophy Points:
    245
    #18
    You can't even have an opposing view on this. We are talking about writing clean code vs bad code. It's like someone arguing to remove dangerous mode from a House and another coming along and saying "it has it's place". It makes zero sense. I think you have no idea what you are talking about. Or you have no idea what is being talked about by the mention of "clean code".
     
    NetStar, Jul 4, 2017 IP
  19. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,998
    Best Answers:
    253
    Trophy Points:
    515
    #19
    That's the rub though, the only hack I see there is tables for layout... the rest of it is just bloated shit code that probably took ten times longer to create and outputs easily three times or more than what it should. Hacks do have their place -- it's called in the stylesheet. The EXTERNAL stylesheet.

    Static style in the markup isn't a hack, it's shitty coding that 99.99% of the time has zero business on a website. "onevent " attributes aren't hacks, they're outdated outmoded shit code that have no business on a website (especially since if someone decides to add the CSP, they cease to EXIST). Using onevent attributes to do CSS's job, that's just plain shit no matter how you look at it, ALWAYS has been! Same can be said of the endless pointless idiotic use of Element.style!!!

    ... and that's before we talk the inaccessible malformed form, gibberish use of numbered headings, multiple echo doing single echo's job, multiple echo doing a single echo's job, double quoted strings just making output harder to code, multiple <?php for no good reason, manual /n doing the job of just formatting your bloody output, line-breaks and non-breaking spaces doing padding's job, etc, etc, etc...

    Which is why there is likely ZERO reason for that to vary significantly from:

    
    <?php
    
    $current_user = wp_get_current_user();
    $user_video_pref = get_user_meta($current_user->ID, 'namespace_video_size_pref', true);
    $arr = [
    	'Large' => '960x540',
    	'Medium' => '720x406',
    	'Small' => '320x180',
    	'Auto' => 'Auto'
    ];
    
    echo '
    	<form method="post" action="', the_permalink(), '" class="radioImageSizes">
    		<fieldset>';
    
    foreach ($arr as $name -> $value) echo '
    			<div>
    				<input
    					type="radio"
    					name="namespace_video_size_pref"
    					id="namespace_video_size_pref-', $value, '"
    					value="', $value, '"', (
    						$value == $user_video_pref ? ' checked' : ''
    					), '
    				>
    				<label for="namespace_video_size_pref-', $value, '">
    					<span>', $name, '</span>
    					<img
    						src="http://images.namespace.com/', $value, '.gif"
    						alt="Choose ', $name, ' image size"
    					>
    				</label>
    			</div>';
    
    echo '
    		</fieldset>
    		<div class="submitsAndHiddens">
    			<button type="submit" name="action" value="update user">Update</button>
    			<!-- I'd have a random expiring session hash here to prevent re-use or unauthorized use -->
    		</div>
    	</form>';
    
    Code (markup):
    With EVERYTHING else done in an external stylesheet, maybe with a small polyfill script to replicate CSS3's :checked attribute for IE8/earlier. You slopped 2.8k of PHP in there to do 1.13k of code's job. That slop outputs around 6.5k of bloated presentational scripttard rubbish doing the job of somewhere under 2k of markup's JOB... and really if that took more than a K of modern CSS to replace your scripting, and 2k of polyfills for :checked, I'd be shocked... but that's what happens when you shit all over the place with onevent attributes doing what should be hooks, and screw around with Element.style to do what should be a simple class swap for pre-CSS3 support.

    If the rest of the site was coded in a similar fashion, Of COURSE IT FAILED!

    Naturally I'd have said it was doomed to "also ran" status at best, failure as most likely scenario the moment I saw "wp_get_current_user", since I know full well what that implies so far as train wrecks of developer ineptitude is concerned. The cute TOY for making blogs for grandma, that has ZERO business being used on anything business related. Websites soiling their own bedsheets with static style in the markup, endless pointless classes for nothing, and "Semantic markup, what's that?" are pretty much par for the course when the shitstorm of ignorance, ineptitude, and incompetence that is turdpress gets involved!
     
    deathshadow, Jul 4, 2017 IP