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 🙂

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.

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.

git – pushing a new local branch to remote

Introduction

There are a few things that I have to do regularly in “git”, but have a gap of a few weeks between each time I do them. This gap is just long enough me to not bother remembering them, so I find myself googling these things again and again – so here’s the first of my regular but infrequent things I have to do in git…

Pushing a new local branch to remote

git push -u origin local-branch-name

which should give something like this…

Counting objects: 71, done.
Delta compression using up to 2 threads.
Compressing objects: 100% (36/36), done.
Writing objects: 100% (37/37), 530.39 KiB | 365 KiB/s, done.
Total 37 (delta 28), reused 0 (delta 0)
To ssh://nas2/dw_git/rpd_deploy.git
 * [new branch] local-branch-name -> local-branch-name
Branch local-branch-name set up to track remote branch local-branch-name from origin.