Code From Hell

There are a lot of code zealots out there who pretend to think that their chosen language is the best language ever and anyone who uses another language is dumb. I’ve lost count of the PHP vs Java, or ‘language a’ vs ‘language b’ debates I’ve seen. Sometimes it comes down to personal choice, sometimes a certain language is a better option for the task at hand and sometimes it really doesn’t matter. Personally whilst I do like certain languages I have never ruled out other languages simply because I don’t like them. Better is nearly always a matter of opinion.

What does hold universal though is that no matter what language you use there are always people who produce poor code in them. And then there are people who produce code so bad that they give programmers a bad name. As a long time reader of the blog Daily WTF you can find so many examples of bad code in just about any language, and during my career I’ve come across code which could make many an article. Recently however I have been cursed with working on a code base that is so monumentally bad that I feel compelled to share some of the best snippets. Warning: what follows may make you weep!

Has it been obfuscated?

There are functions (but not all) in the code base that simply look like they have been obfuscated, variable names have been replaced with what looks like machine generated names. That is until you look closer and you realise that no obfuscation program could be so inconsistent. Mixed amongst the seemingly generated variable names is the odd variable name that makes sense. Take this example below:

get_page_game() {
  if(isset($_SESSION['auth']['uid'])) {
    $uid=$_SESSION['auth']['uid'];
    $ip=$_SERVER['REMOTE_ADDR'];
    $date=date('Y-m-d');
    if(isset($_POST['gameID'])) {
      $i0l1101=isset($_POST['userID'])? preg_replace('/[^\d]/','',$_POST['userID']) : 0;
      $i0l11010=isset($_POST['gameID'])? preg_replace('/[^\d]/','',$_POST['gameID']) : 0;
      $i0l110101=isset($_POST['highscore'])? preg_replace('/[^\d]/','',$_POST['highscore']) : 0;
      $i0l1101010=isset($_POST['wpm'])? preg_replace('/[^\d]/','',$_POST['wpm']) : 0;
      $i0l11010101=isset($_POST['userStage'])? preg_replace('/[^\d]/','', $_POST['userStage']) : 0;
      $i0l110101010=isset($_POST['userSpeed'])? preg_replace('/[^\d]/','', $_POST['userSpeed']) : 0;
      $i0l1101010101=isset($_POST['userUnlocked'])? preg_replace('/[^\d]/','', $_POST['userUnlocked']) : 0;
      $i0l11010101010=isset($_POST['incrementLevel'])? preg_replace('/[^\d]/','', $_POST['incrementLevel']) : 0;
      $i0l110101010101=isset($_POST['wpmTarget'])? preg_replace('/[^\d]/','', $_POST['wpmTarget']) : 0;
      $il1l1l1010101011=isset($_POST['lettersTyped'])? preg_replace('/[^\d]/','', $_POST['lettersTyped']) : 0;
      $ill00=database::query("SELECT `nickname`,`grpname`,`stage`,`lvldata`,`maximum_score` FROM `ft_account_members` WHERE `uid`='$i0l1101'");
      while($ill001=mysql_fetch_array($ill00)) {
        $i00l1101010101010=$ill001['nickname'];
        $i00l11010101010101=$ill001['grpname'];
        $hlvldata=$ill001['lvldata'];
        $i00l110101010101=$ill001['maximum_score'];
      }
      $i1l01ll0= 'ft_64m3'.$i0l11010;
      $ill0010=database::query("SELECT `highscore` FROM `".$i1l01ll0."` WHERE `nickname`='$i00l1101010101010'");
      if(mysql_num_rows($ill0010)>0) {
        $ill00101=mysql_fetch_array($ill0010);
        if(mysql_error()=='') {
        }
        else { 
          echo mysql_error();
          exit();
        }
        ...
      }
    }
  }
}

Variables look generated, $i, $i1i, $i10 etc but then you look closer and realise some of 1’s are actually l’s, which conceivably could be generated, but then right in the middle is $hlvldata. Huh? either it has been obfuscated and the obfuscater is unbelievable or the variable names have been purposely chosen!

Ever heard of a loop?

So what do you do if you want to assign 32 variable names in ascending numerical order. Why you write it our 32 times of course, and of course you do this in at least 10 functions as well just for good measure.

$mpm->assign('gs0',$mp->get_game0score());
$mpm->assign('gs1',$mp->get_game1score());
$mpm->assign('gs2',$mp->get_game2score());
$mpm->assign('gs3',$mp->get_game3score());
$mpm->assign('gs4',$mp->get_game4score());
$mpm->assign('gs5',$mp->get_game5score());
$mpm->assign('gs6',$mp->get_game6score());
$mpm->assign('gs7',$mp->get_game7score());
$mpm->assign('gs8',$mp->get_game8score());
$mpm->assign('gs9',$mp->get_game9score());
$mpm->assign('gs10',$mp->get_game10score());
$mpm->assign('gs11',$mp->get_game11score());
$mpm->assign('gs12',$mp->get_game12score());
$mpm->assign('gs13',$mp->get_game13score());
$mpm->assign('gs14',$mp->get_game14score());
$mpm->assign('gs15',$mp->get_game15score());
$mpm->assign('gs16',$mp->get_game16score());
$mpm->assign('gs17',$mp->get_game17score());
$mpm->assign('gs18',$mp->get_game18score());
$mpm->assign('gs19',$mp->get_game19score());
$mpm->assign('gs20',$mp->get_game20score());
$mpm->assign('gs21',$mp->get_game21score());
$mpm->assign('gs22',$mp->get_game22score());
$mpm->assign('gs23',$mp->get_game23score());
$mpm->assign('gs24',$mp->get_game24score());
$mpm->assign('gs25',$mp->get_game25score());
$mpm->assign('gs26',$mp->get_game26score());
$mpm->assign('gs27',$mp->get_game27score());
$mpm->assign('gs28',$mp->get_game28score());
$mpm->assign('gs29',$mp->get_game29score());
$mpm->assign('gs30',$mp->get_game30score());
$mpm->assign('gs31',$mp->get_game31score());
$mpm->assign('gs32',$mp->get_game32score());

For the love of Deity man have you never heard of a loop? Perhaps he’d tried it as dynamic method calls and it didn’t work for him, oh wait no he’s already used a dynamic method call in another function, so that can’t be right.

Oh yeah and check out the variable names, no $iiii this time, and unbelievably where this is used multiple times the variable names are different, so it isn’t just a cut and paste jobbie???

Ever heard of date functions?

Damn you MySQL and your weirdly formatted dates, I don’t understand them, if only I could make them more friendly? I know I can split the date up and then change it – how could this be coded?

switch($hMonth) {
  case 1: 
    $hMonth='Jan';
    $hValue=1;
  break;
  case 2: 
    $hMonth='Feb';
    $hValue=2;
  break;
  case 3: 
    $hMonth='March';
    $hValue=3;
  break;
  case 4: 
    $hMonth= 'April';
    $hValue=4;
  break;
  case 5: 
    $hMonth='May';
    $hValue=5;
  break;
  case 6: 
    $hMonth='June';
    $hValue=6; 
  break;
  case 7: 
    $hMonth='July';
    $hValue=7;
  break;
  case 8: 
    $hMonth='Aug';
    $hValue=8;
  break;
  case 9: 
    $hMonth='Sep';
    $hValue=9;
  break;
  case 10: 
    $hMonth='Oct';
    $hValue=10;
  break;
  case 11: 
    $hMonth='Nov';
    $hValue=11;
  break;
  case 12: 
    $hMonth='Dec';
    $hValue=12;
  break;
}

Maybe its because he wanted to be as inconsistent with the date month display as he is with his variable names? There are so many shorter ways of doing this, let MySQL spit the date out in a correct format, use strtotime() coupled with date()? Argghh it hurts its too painful.

Ever heard of a sane data structure?

This last example takes the biscuit though. As far as I can tell what the coder wanted to do was store a set of 3 data points representing level scores. How did he choose to do this? in the date format 1_1.1_2.1_3.2_1.2_2.2_3….. thats right as a ‘.’ separated list with a ‘.’ set separator! How the hell would this be read in and updated… like this:

$a0=array("a00"=>array(
  0=>0,1=>0,2=>0,3=>0,4=>0,5=>0,6=>0,7=>0,8=>0,
  9=>0,10=>0,11=>0,12=>0,13=>0,14=>0,15=>0,16=>0,
  17=>0,18=>0,19=>0,20=>0,21=>0,22=>0,23=>0,24=>0,
  25=>0,26=>0,27=>0,28=>0,29=>0,30=>0,31=>0,32=>0
));
$a1=array("a11"=>array(
  0=>0,1=>0,2=>0,3=>0,4=>0,5=>0,6=>0,7=>0,8=>0,
  9=>0,10=>0,11=>0,12=>0,13=>0,14=>0,15=>0,16=>0,
  17=>0,18=>0,19=>0,20=>0,21=>0,22=>0,23=>0,24=>0,
  25=>0,26=>0,27=>0,28=>0,29=>0,30=>0,31=>0,32=>0
));
$a2=array("a22"=>array(
  0=>0,1=>0,2=>0,3=>0,4=>0,5=>0,6=>0,7=>0,8=>0,
  9=>0,10=>0,11=>0,12=>0,13=>0,14=>0,15=>0,16=>0,
  17=>0,18=>0,19=>0,20=>0,21=>0,22=>0,23=>0,24=>0,
  25=>0,26=>0,27=>0,28=>0,29=>0,30=>0,31=>0,32=>0
));

$hlvldataii=$hlvldata;
$hlvldatatok0=strtok($hlvldataii,".");
$hCntTok0=0;
$hCntTok1=0;

while($hlvldatatok0 !== false) {
  if($hCntTok1==0)$a0["a00"][$hCntTok0]=$hlvldatatok0;
  if($hCntTok1==1)$a1["a11"][$hCntTok0]=$hlvldatatok0;
  if($hCntTok1==2){
    $a2["a22"][$hCntTok0]=$hlvldatatok0;
    $hCntTok0++;
    $hCntTok1=0;
    $hlvldatatok0=strtok(".");
    continue;
  }
  $hlvldatatok0=strtok(".");
  $hCntTok1++;
}

$hlvl=$hCntTok0-1;
$hFlg=0;

for($i=0;$i<$user_stage;$i++) {
  $hlvlSrch.=$a0["a00"][$i].'.'.$a1["a11"][$i].'.'.$a2["a22"][$i].'.';
}

$hlvlSrch .= $user_stage.'.'.$wpm.'.'.$wpm_target;

I don't even know where to begin with this, have a go yourself, of course the variable names have been designed to help legibility. I wanted so badly to re-write it but in the end I opted to leave it as is and grab a beer.

Kill me now!

I could go on, these examples are just insane, the rest of the code is no better, if statements 20 levels deep, the same code repeated in a dozen functions, a single file with over 4000 lines of code. I can honestly say this is some of the worse code I've ever had the misfortune to work on.

Unfortunately I had to inform the client of how bad the code was, embarrassed at the level of incompetence displayed by my profession. Fortunately she was very understanding and guided by me has taken the wise decision to let me throw it away and start again. Hopefully a happy ending!!!

Perch CMS

When it comes to CMSes you could say I have a fair amount of experience. Practically every site I have ever worked on has had some aspect of content management, most of which I or my ex-team has built from the ground up. You could say that I am a big fan of bespoke content management systems.

The reason I am such a big fan is that when it comes to adding content management you can make a fair bet that an off the shelf package or an open source CMS would only work for 90% of the sites functionality. What you end up having to do is customise the packaged CMS for your purposes or have to compromise on functionality for the site. Customisation is usually in the form of a plug-in, and these come with their own headaches. Your upgrade path is compromised, security is even further out of your control and the quality of plug-ins is rarely as high (or low) as the original package.

This is all well and good if you have budget to play with, but in my experience 75%+ of the time content management is overkill for a site and never actually used by the client. They pay the bills though and usually against advice it is required, and on every page! Can I add a CMS for every page, you bet I can and with the use of a good MVC framework it is a lot simpler and quicker to implement than it used to be. But lets face it its tedious, of no technical challenge and budget could be better spent elsewhere on the UI.

This is obviously an issue which isn’t confined to just me and one I guess a number of people have tried to fix. What I need is a simple CMS that can be quickly implemented for a simple site. Step into the light Perch.

Perch has been developed by edgeofmyseat and its tagline is

a really little content management system

I’ve heard good things about this off the shelf package so on a recent project after debating whether I would find myself having an awful time wrestling with yet another system which didn’t do what I wanted I decided to give it a go. Lets just say I wasn’t disappointed.

Lets also be clear from the start the use-case for this was a very simple site with what amounted to one template over a fixed number of pages. I didn’t need the ability to add new pages, I controlled the layout, and the template was fixed into three types, a heading, body content and an image/video.

After buying a very reasonably priced license I set about installing the system. Given I am very comfortable in using frameworks, wordpress, drupal, joomla and the myriad of other similar packages the installation was very simple. A config file, a slight customisation to the URL and the CMS was installed. Total time from starting to having it up and running 12 minutes. Even in comparison with wordpress that was quick!

Now I had the system running I needed to see if it did what I needed. Having already built the site template I looked at the example page the CMS came with and amazingly it satisfied 2/3rds of my needs. Copy and paste later and the page was defined. Visit the page in my browser and Perch picked up on this installation and displayed the content to be edited in the admin screen. Simple as that. I won’t go into details as to how it worked as the documentation does a much better job than I ever could.

So far everything had been ridiculously easier but the last part was not an out of the box solution, the dammit I wish I could do this moment I had been dreading. The requirement was to be able to upload either a video or an image to display next to the content.

Perch has certain types of content, and templates which define collections of content types. I decided to create my own template that utilised the file and image types with a conditional to define which one to use. My first thought was that I could use a radio button to determine which of the two types to display, unfortunately I couldn’t work out how to target a specific content value through the conditional tag, it seemed only to define if the the option had a value of any type. I changed it to a checkbox which meant the page defaulted to an image but could be overridden with a video.

The template was defined like this (content has been slightly mangled by the syntax highlighter):



  
    <script src="/js/flowplayer-3.2.6.min.js"></script>
    
<script> flowplayer("player", "/flash/flowplayer-3.2.7.swf", { clip: { url: "<perch:content id="file" type="file" label="Video" order="2" />", autoPlay: false } }); </script>

This was saved as template and could then be assigned to the content region when I added it to the page. This worked very well for me and I had essentially finished the CMS in less than 2 hours! What more could I ask for than that. Well I would of course have preferred my original template implementation, and the ability to restrict the file type for upload would also have been nice but I could trade-off these requirements for the speed of implementation.

So would I recommend Perch? In a word yes, in a sentence it would be yes if your use case hits the demographic its aimed at? My use case was simple, very simple and even with a custom template it practically worked out of the box. If your CMS requirements are more complex I would think twice about using Perch. Now that’s not to say Perch cannot but manipulated to your needs, its got a great API and some great looking plug-ins but then you are back to where you are with most off the shelf CMSes. If you need a lot of custom pages and custom CMS flows then I would probably go back to bespoke in a flash. Maybe thats because I haven’t had the chance to get deeper into Perch and perhaps I should.

However if you get a chance to use Perch I would highly recommend it.

AB Development Site Launch

Today sees the launch of my own site AB Development. It has officially been in development from start to finish for the last month on and off. Its nothing complicated and shouldn’t have taken me so long to develop but what I can say is that the site is mine, designed and built from the ground up.

Its certainly not the most creatively inspiring piece of work but its not meant to be, it is designed for function not to create an experience. I’ve been using, where appropriate, a lot of what I have been experimenting with over the past year in this blog. It is specifically built not to act the same in all browsers, I’m not interested in breaking my back making it look exactly the same in all browsers. I have used a lot of progressive enhancement to make it look better in browsers with better CSS support, but not look too bad in other browsers either.

What have I used?

  • A HTML5 doctype, the site isn’t necessarily HTML5 but I needed a doctype to trigger standards mode and the HTML5 doctype is as good as any.
  • Reset v2.0, recently released by Eric Meyer, again in keeping with the HTML5 doctype.
  • A grid system, more specifically I have used the 960 grid system as the basis for the design
  • CSS3 has been liberally applied to produced the alpha transparency effects, rounded corners and text shadows. Don’t have a browser which supports CSS3, well there are fallbacks in place for these browsers courtesy of CSS3 please!
  • JQuery has been used, with a few plugins for the menu, and scroll behaviour, and the also the form submits via AJAX.
  • Twitter feed uses the widget provided by twitter in their resource site, it was customised using CSS

I haven’t fully tested the site in all browsers, but have looked at it in IE6, 7 and 8. Unsurprisingly there were a number of bugs found and surprisingly they were easy to fix to the extent where the site was both functional and visually stable. There is probably more work to do here. Similarly I haven’t provided a fallback mechanism for the form as yet, so if you don’t have <a href="http://trpdsaya.tumblr.com/post/3482973219/i-wonder-if-this-site-will-degrade-gracefully-if-i" onclick="_gaq.push(['_trackEvent', 'outbound-article', 'http://trpdsaya.tumblr dig this.com/post/3482973219/i-wonder-if-this-site-will-degrade-gracefully-if-i’, ‘javascript enabled’]);” target=”_blank”>javascript enabled you can’t submit the form as yet. No doubt these little additions will be dealt with over time.Movie Fifty Shades Darker (2017)

In the immortal words of Neil Crookes, abdevelopment.co.uk CHECK IT OUT!

Starting my own business

This blog last year was devoted to me developing and re-skinning the site slowly using the latest web standards and development techniques. This year hopefully the blog will be devoted to me documenting a new career and business.Movie Passengers (2016)

As I said in my review of 2010 my employment status has changed for the first time since late 1999. After 11 years at LCG working for Five by Five I took redundancy just before christmas without a really good plan for the future. This could be described as a bit foolish given that I now have a family to provide for with the usual burden of a mortgage and some of the most challenging financial times in recent history. Fortunately for me 11 years redundancy payment has eased the urgency for a solid plan and has afforded me with the opportunity to try something new on my own terms.

Since christmas I have slowly eased myself into January with a very rough plan of going it alone. Admittedly I haven’t thrown myself into things tooth and nail as yet given the lack of money urgency, and basically I’ve given myself January to do a few bits and pieces before hopefully kicking on. Whilst I’ve always thought about going it alone I’ve always worried about jumping in given the lack of financial safety net, I’ve also also worried about my own personal motivation levels which haven’t always been high recently. But most of all is the fear of actually having to get the work, I’ve no worries about my being able to deliver as I have very solid development skills, but can I find the work, and will it be in enough quantity and of high enough value to make ends meet in the long-term?

So far I’ve done a bit of reading into starting a business and to be honest I haven’t found a resource which is straightforward and answers some of my basic questions. The business link is a great place to start and has a comprehensive level of information but the sheer amount of information is a little overwhelming and I found myself flitting from one question to another without really getting anywhere. Fortunately I have some good friends who have all been through this themselves already so I’ve found myself leaning on these friends for advice to answers such questions. So here’s my first bit of advice, if you have some friends who have experience, tap into it!

I’ve a list of things to do which whilst isn’t comprehensive certainly gets me started:

  • Name the company
  • Buy a domain name
  • Create a brand (logo)
  • Develop a web presence
  • Define service list
  • Set up as self employed
  • Get a business account
  • Get some work!

So far I’m not far down the list, I’ve got a name – AB Development – and I’ve bought the domain name but essentially that is it. I’ve got a good idea of my list of services, to start with it will be full service web development, in the future it will hopefully also include iOS development. Stay tuned as I work my way down the list, and in the meantime if you need a freelance web developer, or have a development need for yourself please get in touch.