Burning tree image

Working code isn’t enough #2

This is the second in (what is apparently becoming) a series of posts about good and bad coding styles from my personal perspective.

In each post I show two possible fully working solutions to a code problem to highlight the opposite extremes of what I feel are good and bad programming styles.

Problem: The Path Problem on TestDome

https://www.testdome.com/questions/php/path/12285?questionIds=7278,12285&generatorId=30&type=fromtest&testDifficulty=Hard

Bad Solution

  public function cd($newPath)
  {
    if ($newPath[0]!=='/') {
      $this->currentPath = implode('/',array_reduce(explode('/',$newPath),function($new, $cd){
        return ($cd=='..')?array_slice($new,0,-1):array_merge($new,[$cd]);
      },explode('/',$this->currentPath)));
    } else {
      $this->currentPath = $newPath;
    }
  }

Good Solution

  const SEPERATOR = '/';

  public function cd($newPath)
  {
    // turn our path strings into arrays to simplify processing ----------
    $currentPathBits = explode(static::SEPERATOR, $this->currentPath);
    $cdPathBits = explode(static::SEPERATOR, trim($newPath));

    // check for special cases -------------------------------------------
    if (count($cdPathBits) == 0) {
      // no path change specified so nothing to do
      return;
    }
    if ($cdPathBits[0] == '') {
      // absolute path specified - so reset $currentPathBits
      $currentPathBits = [];
    }
 
    // core path bit processing ------------------------------------------
    foreach ($cdPathBits as $cdPathBit) {
      switch ($cdPathBit) {
        case '..':
          // move up a directory - remove the last bit of the current address bits
          array_pop($currentPathBits);
          break;
        case '.':
          // current directory - nothing to change in this situation
          break;
        default:
          // new directory bit - so append it to the path
          array_push($currentPathBits, $cdPathBit);
          break;
      }
    }
 
    // now turn the $currentPathBits back into the path string -----------
    $this->currentPath = implode(static::SEPERATOR, $currentPathBits);
  }

Is the good vs badness self explanatory? Maybe not. The Bad solution is very clever isn’t it? Aren’t I showing off how clever I am. How well I can wield the arcane magic that is the shitty PHP core functions. I’ve folded it all together so there’s hardly any wasted characters. And “it works – so what are you complaining about?”

I am complaining! Anyone who writes web or scripting code in that bad solution style and expects it to get into production, is either: showing off; trying to make it impossible to fire them; or pushing up the Autistic Spectrum. And with the exception of the Autist, I refer the others to the reply given in the case of Arkell v. Pressdram

Try writing code that other people can grok. Code that still makes sense to you in 12 months time when you come back to it. Maybe code that even non-developers have a chance of roughly understanding. Code that you can change quickly and safely if a problem is found or a great opportunity requires a nimble pivot.

If anyone ends up reading any of these and is interested in discussing why I think they’re good and bad, I’m up for that 🙂

 

Working code isn’t enough #1

This is the first in (what might be) a series of posts about good and bad coding styles from my personal perspective.

In each post I’m going to show two possible fully working solutions to a code problem to highlight the opposite extremes of what I feel are good and bad programming styles.

Problem: Thesaurus question on TestDome

https://www.testdome.com/questions/php/thesaurus/7278?questionIds=7278,12285&generatorId=30&type=fromtest&testDifficulty=Hard

Bad Solution

    public function getSynonyms($word)
    {
        return json_encode(['word'=>$word,'synonyms'=>@$this->thesaurus[$word]?:[]]);
    }

Good Solution

    public function getSynonyms($word)
    {
        $synonyms = [];
        if (array_key_exists($word,$this->thesaurus)) {
            $synonyms = $this->thesaurus[$word];
        }
 
        $result = [
            'word'=>$word,
            'synonyms'=>$synonyms,
        ];
        return json_encode($result);
    }

Hopefully the good vs badness is self explanatory, but if anyone ends up reading any of these and is interested in discussing why I think they’re good and bad, I’m up for that too 🙂

Ivybridge Town Council leaps forward into the 20th Century

The latest Ivybridge Town Council meeting has been videoed and is available for viewing at this url:

Please share this and spread the word – the very best thing that Ivybridge residents can do is let their Councillors know they will be held to account – and having a few views on that video will certainly do that !

…and yes, I know the 20th Century ended over 17 years ago 😉

Leaving drinks

Today is my last Friday in the office I’ve been sharing with three friends (and local businesses people).

A few years ago we all used to have a Friday drinks tradition where we’d sit around and chat about our businesses and how we were getting on, and at some point it kind of fizzled out.

So we (mini) resurrected it this evening and hopefully a good time was had by all.

On Tuesday next week I’ll be moving into my new office on the Tamar Science Park which should be an interesting new chapter for the business.

Cheap sausages

Almost forgot to blog today – well it’s technically tomorrow already, but I’m not asleep yet, so let’s pretend.

Sausages. We had sausages in baps tonight for dinner with dry fried onions.

It was all a bit last minute though, and Debs (my better half) just brought a packet of sausages from our local Co-op.

Now I’ve been working from a shared office above a really good butchers since January, and it’s been very easy to get brilliant fresh sausages from them. (and the best lean streak mince ever too!)

But you don’t realise how good, good meat is, until you go back to the old cheap supermarket dross. And when I say cheap I mean cheap ingredients, because the actual cost of the sausages is virtually the same anyway.

So support your local butcher and revel in the taste of their sausages. Reject mass produced crappy food.

Hoorah.

The cost of a broken PC.

My brother phoned today in some distress. After a few quick questions it became clear his PC had likely died. Checking in person later in the day it became evident that either the power supply, motherboard, or possibly the CPU was the victim.

Now this is a 4+ year old Dell that has served him well, so doesn’t really owe him anything. But wow, what a price we pay for becoming so dependent on the Universal Tool that the PC has become! He needs it replaced, and replaced quickly. Without it he isn’t really in business.

My normal inclination to replace the damaged parts was unfortunately not a viable option. The first reason being that the machine is so old (and was so low spec when built), that sourcing equivalent parts proved difficult.  The second reason being the time it would take to establish what was and wasn’t working once we had the parts, and trying to get refunds on the bits it would likely turn out we didn’t need.

So now I finally understand why otherwise seemingly intelligent people purchase PC’s from high street stores like PC World.

The ease with which he could save 10’s if not 100’s of £’s by shopping online is balanced by the ability to be able to walk out 1 hour later with a working PC. That is obviously worth the extra money to some people.

In the end though he ordered a replacement from Dell. A “better the devil you know” scenario. Reasonable value for money and a reasonable expectation of getting at least another 4 years out of it.

But I’m still left wondering how impulse buyers and business people who will loose money if they don’t have a machine right now, are a big enough market to keep the likes of PC World in business?

Yet more proof (if it were even needed) that people really DO NOT BUY ON PRICE ! (even though they believe they do).

WordPress business Podcast

I’m moving my business to a new office at the end of the month, which is going to involve a 15 minute drive every morning and every evening.

Now I used to listen to lots of podcasts back when I commuted to London every day. But for the last 4 years I’ve not done any regular journeys long enough to get a proper listen in.

So you can appreciate my surprised at how many WordPress specific podcasts there are. And so many are of great quality.

But I’d like to single one out today as the one that’s top of my list for my new commute…

The MattReport.com

For those who don’t know, it’s a rather excellent interview format podcast focused on the business of being in business in the WordPress economy.

Matt Medeiros, the host, has a relaxed approach and puts his interviewees at ease, which really enables him to draw deep detail out of them.

Most importantly though he asks really interesting questions, which, as someone at the early stages of building a WordPress oriented software business myself, are spot-on of interest to me.

Props to Matt & the MattReport.com

A couple of days of A Year Without Pants

I brought my most expensive eBook a couple of days ago – A Year Without Pants by Scott Berkun as a kindle book.

At £11.01 it costs many times more than the next most expensive one I’ve brought up until now. But up until now I’ve only been buying SciFi books.

A Year Without Pants is an ‘inside’ view of working within Automattic, the private company behind the WordPress.com website. Automattic is unique in the way it operates. All staff are remote employees, and the management hierarchy is incredibly flat.

This is of particular interest to me as I’ve been pretty much constantly over-subscribed with work in my business for about the last 4 months. I need to change how the business works, and one obvious possible change would be to spread the workload over more people than just me!

I’ve only read about 30% of the book so far, but can say it’s very well written, with a very easy to read style, and a good mix of humour and information.

I’m stunned, so far, at how different Automattic’s structure is – especially compared to the many Investment Banks I’ve worked with in the past. And yet Automattic continues to operate in an incredibly lean way and consistently pushes out reasonably high quality product.

There’s lots to learn from Automattic, and I’m looking forward to digging deeper. And I recommend A Year Without Pants by Scott Berkun to anyone interested in exploring new models of employing staff.

Evil Gingerbread Man

Our youngest, Matt, brought us a ‘make your own Gingerbread Man’ kit for the family to share.

This was my attempt at an ‘Evil Gingerbread Man’. Not entirely sure what the sweet adornments are supposed to represent.  A heart and a codpiece maybe?

image

Consolidated blogging for simplicity

Having done various bits of ‘low-profile’ blogging all over the place for the last few years,

I’ve decided to consolidate my efforts into this single blog – so from now on – this is where I’ll be doing my personal blogging, and my ‘commercial’ blogging will all be on davelopware.com.

Anywhere else that I want to spout about stuff – I should be doing it on these blogs, and posting links back in the other contexts!

So here it is – I publicly commit to blogging at least once a week commercially, and every day personally.

Hmm – there it is – out there – let’s see how that goes then.