Well that was embarrassing! Day 1 of a plugin release. One of my first customers. Boom, Fatal Error. (╯°□°)╯︵ ┻━┻

In short, it was a simple mistake on my part, by using a function in PHP that wasn’t supported by versions of PHP lower the 5.3. Now, some of your purist developers and site owners might think “Well, that’s their fault for not having a modern version of PHP”. Let me remind you, WordPress still requires PHP 5.2.4 or greater. I write WordPress plugins, therefore I must support PHP 5.2.4 or greater. I’ll take full responsibility for that.

So what did I do wrong? Well, PHP 5.3 introduced ‘closures’, or what other languages call “Anonymous Functions”. The line of code in question was this:

$utm_string .= implode( '&', array_map( function ( $v, $k ) { return 'utm_' . $k . '=' . $v; }, $utm, array_keys( $utm ) ) );

To be completely honest, this line of code should have been (and was actually replaced by) a simple foreach loop. So why didn’t I do that? Simple answer is, I was looking for a ‘fancy’ way to make it a one liner. Closures are a powerful tool and can be used very intelligently…if your sure that the version of PHP being used is new enough. In this case, it was just a ‘tricky’ way to make 6 lines into 1. Here’s the replaced code:

$first = true;
foreach ( $utm as $key => $value ) {
    if ( !$first ) {
        $utm_string .= '&';
    }
    
    $utm_string .= 'utm_' . $key . '=' . $value;
    $first = false;
}

See, minus whitespace and brackets, 6 lines of code. So stop being tricky developers! just take a few extra minutes to do it the compatible way. You AND your users will thank you later. Still not convinced? Great, here’s a few more reasons why tricky code is a bad idea.

1. Tricky code is NOT readable

Look at that line I wrote above. Not the nice foreach…but that monstrosity of a single line. That thing is not easy to read. The variables are named poorly. No whitespacing, and it just reads like a compiled mess. We use non-compiled languages for a reason, and it’s so we don’t have to look at crap like that.

2. Tricky code is NOT safe

Finding a tricky unique way to make a shortcut usually isn’t backwards compatible. Think about it, the tricky way exists in the version you are using, because over time we’ve grown to find a need for a shorter method. Older versions of the platform may not have that ability.

3. Tricky code is NOT easily debugged

I’ll draw your attention again to Exhibit A. How would you put debug code into that thing? Not easily right? You’d be having to count brackets, and make sure you’re in the right method. Now compare that with the simply foreach loop. We could easily throw a line or two of debugging in there without having to worry about breaking the logic.

Look, I’m not opposed to using clever methods to do things. That’s what developers do…but when it comes to your customers, just make sure you put their experience before your number of lines of code. I’ll leave you with one quote before I prompt you, and it’s one I love using:

Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.
-Brian Kernighan: Co-Developer of Unix

So what’s one way you’ve been tricky, and how has it hurt (or helped!) you out?

Posted by Chris Klosowski

Chris Klosowski is the Director of Technology at Sandhills Development, LLC, creators of fine WordPress plugins, and ecommerce solutions.

96 Comments

  1. K.I.S.S. principle. You forgot one point: Tricky is not Cool.

    Reply

    1. Yep at the core, keeping it simple is the message. Good point.

      As developers we must remember:
      “With great power comes great responsibility”

      Reply

  2. Great tip! That’s one of the big points of the WP coding standards – http://make.wordpress.org/core/handbook/coding-standards/php/ – to make your code readable and easily debugged (such as using brackets for if statements). Developers often forget about this…I see so many themes/plugins that look like they were coded for no one else but the developer to understand.

    And if you really want to get fancy with some PHP 5.3+ functions best to check the PHP version first, it’s not hard 😉 Like you said, there are still tons of people out there (because of their webhosts mostly) running old versions of PHP.

    Reply

    1. Great point AJ. Thanks for putting the handbook. I always forget to tell people about it…and look, it even has my point exactly listed:

      http://make.wordpress.org/core/handbook/coding-standards/php/#clever-code

      Reply

  3. PHP made things very confusing by saying a closure is an anonymous function.

    But in most other languages (JavaScript, Swift, etc), closures and anonymous functions are different things. In JS a closure encapsulates scope and every function in JS is a closure. But an anonymous function is simply a function with no name and self executing.

    Interesting stuff. I really wish WordPress would raise the version number to something not vulnerable.

    Reply

  4. Hello everyone, it’s Eva here!
    I work as an academic writer and have created this content with the intent of changing your life for the better. I started honing my writing talent in college. I learned that my fellow students needed writing help—and they were willing to pay for it. The money was enough to help pay my tuition for my first semester of college.
    Ever since school, I have continued to work as a professional writer. I was hired by a writing service based in the United Kingdom. Since then, the dissertations that I have created have been sold around Europe and the United States.
    In my line of work, I have become used to hearing, “Eva Mccarthy, can you help me meet my writing assignment deadline?” I know that I can save their time.

    Professional Writer – Eva – tritronicsinc.com Company

    Reply

  5. My partner and I stumbled over here coming from a different page and
    thought I might check things out. I like what I see so
    now i am following you. Look forward to checking out your web page for a second time.

    Reply

  6. Excellent pieces. Keep posting such kind of information on your page.
    Im really impressed by your site.
    Hi there, You’ve done an excellent job. I will certainly digg it and in my opinion recommend to my friends.
    I’m confident they’ll be benefited from this site.

    Reply

  7. ordering viagra 100 mg lowcost viagra – viagra exchange

    Reply

  8. This is a unique place for fashionable women’s clothing and accessories.
    We offer our clients women’s clothing, jewelry, cosmetics and health products, shoes, bags and much more.
    https://Newchic.vip/Zte4

    Reply

  9. Heya i am for the first time here. I came across this board and I find It really
    useful & it helped me out a lot. I hope to give something back and
    aid others like you helped me.

    Reply

  10. or viagra overnight viagra/cialis black and gold 800 – nz viagra online

    Reply

  11. СлотоКинг Казино SlotoKing Casino официальный сайт играть онлайн

    Reply

  12. best prices for viagra generic non prescription viagra premature ejaculation – buy viagra in uk online

    Reply

  13. amoxicillin 500 mg purchase without prescription generic amoxil – amoxicillin buy no prescription

    Reply

  14. zithromax online usa zithromax online – zithromax 600 mg tablets

    Reply

  15. 100mg doxycycline doxycycline tablets – online doxycycline

    Reply

  16. ivermectin lotion for lice ivermectin buy online – stromectol ivermectin tablets

    Reply

  17. п»їorder stromectol online best price on ivermectin pills – how much is ivermectin

    Reply

  18. ivermectin pills human stromectol tablets – ivermectin cream

    Reply

  19. best online canadian pharmacy prescription meds without the prescriptions – natural help for ed

    Reply

  20. medications for ed drug comparison – mens erection pills

    Reply

  21. male erection prescription drugs without doctor approval – remedies for ed

    Reply

  22. ed remedies that really work prescription meds without the prescriptions – cure ed

    Reply

  23. best drug for ed buy prescription drugs without doctor – ed trial pack

    Reply

  24. lipitor 40mg coupon for lipitor – generic for lipitor

    Reply

  25. hydroxychloroquine 25 mg plaquenil – hydroxychloroquine 100mg

    Reply

  26. buy ivermectin canada ivermectin – stromectol ivermectin

    Reply

  27. cost of lipitor 10 mg atorvastatin – lipitor 10 mg cost

    Reply

  28. lexapro 10mg Escitalopram – lexapro generic

    Reply

  29. lexapro medication lexapro – lexapro discount

    Reply

  30. buy real viagra online sildenafil – order viagra online

    Reply

  31. ed for men ed meds pills drugs – prescription without a doctor’s prescription

    Reply

  32. best ed medications ed meds pills drugs – ed natural treatment

    Reply

  33. On the site you can order women’s clothing wholesale and retail from the manufacturer as cheaply as possible.
    A variety of models and a wide range of sizes for the owners of any shape are our strengths that distinguish us from our competitors.
    https://fas.st/iwuYc

    Reply

  34. cialis generic dapoxetine cialis no prescription canada – cialis priligy online australia

    Reply

  35. order clomid online buy clomid – clomid tablet

    Reply

  36. where to buy clomid buy clomid – buy clomiphene

    Reply

  37. where can i buy clomiphene buy clomid – clomiphene for sale

    Reply

  38. Online shop for womens clothing and accessories based in the UK strives to provide high quality products from the most reliable companies in the world.
    We are opening a marketplace for shoppers to find the latest and greatest in-demand products at incredibly low prices.
    https://fas.st/c-wFya

    Reply

  39. treatment for erectile dysfunction prescription drugs without doctor approval – pills for erection

    Reply

  40. clomid generic name clomid tablets – clomid tablet

    Reply

  41. You could definitely see your skills within the
    work you write. The world hopes for more passionate writers like you who
    aren’t afraid to say how they believe. Always go after your heart.

    Reply

  42. cialis with dapoxetine cialis pills – cialis ordering australia

    Reply

  43. zithromax online usa zithromax – buy azithromycin zithromax

    Reply

  44. propecia tablets propecia for sale – cheap propecia pills

    Reply

  45. Magnificent goods from you, man. I’ve understand your stuff previous to and you are
    just too fantastic. I really like what you’ve acquired here, really like what you are saying and
    the way in which you say it. You make it entertaining and you still care for to keep it sensible.
    I can not wait to read far more from you. This is really a wonderful website.

    Reply

  46. buy liquid ivermectin ivermectin for humans where to buy – stromectol australia

    Reply

  47. propecia pills buy propecia – propecia 5 mg for sale

    Reply

  48. can you buy prednisone buy prednisone online australia – generic prednisone pills

    Reply

  49. stromectol generic ivermectin tablets – ivermectin price canada

    Reply

  50. Howdy! Someone in my Facebook group shared
    this site with us so I came to look it over. I’m
    definitely enjoying the information. I’m
    book-marking and will be tweeting this to my followers! Superb blog and wonderful design.

    Reply

  51. Hello! Do you know if they make any plugins to assist with SEO?
    I’m trying to get my blog to rank for some targeted keywords but I’m not seeing
    very good success. If you know of any please share.

    Many thanks!

    Reply

  52. Great goods from you, man. I’ve take note your stuff previous to
    and you are just too magnificent. I really like what you’ve acquired here, certainly like what you are stating
    and the way through which you are saying it.

    You make it enjoyable and you continue to care for to stay it smart.
    I cant wait to learn much more from you. That is really a great
    web site.

    Reply

  53. zithromax prescription online zithromax generic – zithromax z-pak price without insurance

    Reply

  54. ivermectin 1 cream ivermectin for sale – how much is ivermectin

    Reply

  55. stromectol covid 19 ivermectin for humans where to buy – ivermectin online

    Reply

  56. hello!,I really like your writing very a lot!
    share we communicate extra approximately your article on AOL?
    I need an expert in this space to unravel my problem. May be that
    is you! Taking a look forward to see you.

    Reply

  57. generic zithromax azithromycin zithromax – where to get zithromax

    Reply

  58. This is a topic which is close to my heart… Cheers!

    Where are your contact details though?

    Reply

  59. best ed treatment pills ed pills from canada – prescription drugs

    Reply

  60. coupons for cialis cialis buy without – how much is cialis in canada

    Reply

  61. where to buy viagra viagra without a doctor prescription usa – cost of viagra

    Reply

  62. Thanks to my father who told me concerning this weblog, this webpage is genuinely awesome.

    Reply

  63. causes of ed india pharmacies shipping to usa – best pill for ed

    Reply

  64. viagra from india cost of viagra – viagra cost per pill

    Reply

  65. viagra over the counter viagra over the counter – buy viagra online usa

    Reply

  66. natural pills for ed rx online india – cure ed

    Reply

  67. cialis no prescription paypal cialis discounts – viagra vs levitra vs cialis reviews

    Reply

  68. natural ed cures cheap generic drugs from india – what type of medicine is prescribed for allergies

    Reply

  69. Стань королем настоящего средневекового королевства!
    Захватывающая RPG игра и симулятор замка
    https://fas.st/tdhru

    Reply

  70. best online pharmacy for cialis use paypal to buy cialis – viagra cialis melbourne site:au

    Reply

  71. Hi there, You have done a fantastic job. I will definitely digg
    it and personally recommend to my friends. I am sure they will be benefited from this website.

    asmr https://app.gumroad.com/asmr2021/p/best-asmr-online asmr

    Reply

  72. generic cialis no prescription paypal buy cialis brand – buy cialis free shipping

    Reply

  73. ivermectin for sale buy ivermectin – ivermectin for humans

    Reply

  74. Как к примеру, в случае, если у либералов намного больше вероятности выиграть избирательный район, нужно проголосовать за него, когда даже вы ненавидите их.
    Скажем, когда у коммуниста намного больше шансов победить избирательный округ, следует отдать голос за него, если вы лично этого не жаждете.
    Сегодня Алексей Навальный пребывает в тюрьме, и его собственное политическое движение заявлено “противозаконна”, потому оно не имеет права действовать в России.
    По сути своей “Умног голосование” сегодня это политическая стратегия, изобретена российским внесистемным политическим деятелем Алексеем Навальным как средство борьбы с “Единой Россией” умного голосования, проголосовать за главного оппонента кандидата “Единой России” во многих одномандатных округах везде по стране, вне зависимости от общественно-политической принадлежности и взглядов этого соперника.
    Значение представленной стратегии подрезать крылья власти Единой России, а не гарантировать успех любого другого общественно-политического движения.

    реклама умного голосования

    Reply

  75. Hi there to every body, it’s my first pay a quick visit of this
    website; this blog consists of amazing and actually good stuff in support of
    readers. quest bars http://bit.ly/3jZgEA2 quest bars

    Reply

  76. ivermectin 10 mg buy ivermectin online – buy ivermectin cream

    Reply

  77. ivermectin over the counter buy ivermectin – ivermectin 80 mg

    Reply

  78. When someone writes an piece of writing he/she retains the thought of a user in his/her mind that how a user can be
    aware of it. Thus that’s why this paragraph is great. Thanks!

    scoliosis surgery https://0401mm.tumblr.com/ scoliosis surgery

    Reply

  79. I have been exploring for a little bit for any high quality articles or blog
    posts on this kind of area . Exploring in Yahoo I eventually stumbled upon this site.
    Reading this info So i am satisfied to show that I have
    a very good uncanny feeling I found out just what I needed.
    I such a lot undoubtedly will make certain to don?t overlook this site and
    give it a look on a relentless basis. cheap flights http://1704milesapart.tumblr.com/ cheap flights

    Reply

  80. Hi to every one, it’s truly a nice for me to go
    to see this web page, it includes helpful Information.
    quest bars https://www.iherb.com/search?kw=quest%20bars quest bars

    Reply

  81. ivermectin for humans buy ivermectin – ivermectin gel

    Reply

  82. Simply desire to say your article is as astonishing.
    The clarity in your publish is just nice and i could think you’re a professional in this
    subject. Well with your permission let me to clutch your feed to keep updated with
    coming near near post. Thank you a million and please carry on the enjoyable
    work. scoliosis surgery https://coub.com/stories/962966-scoliosis-surgery scoliosis surgery

    Reply

  83. I always emailed this blog post page to all my associates, as if like to
    read it next my contacts will too. ps4 games https://j.mp/3nkdKIi ps4 games

    Reply

  84. generic ivermectin cream cheap ivermectin – ivermectin canada

    Reply

Leave a reply

Your email address will not be published. Required fields are marked *