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
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 🙂