Code Example Demonstrating “Explicitness over Implicitness”

posted by Matías E. Fernández

This code example by Raffael Schmid demonstrates the importance of the core principle titled Explicitness over Implicitness.

Implicit Bash Script

#!/bin/sh

operating_system=$(lsb_release -sc)

case $operating_system in
  precise)
    # Do stuff specific to Ubuntu 12.04 codenamed Precise Pangolin
    ;;
  *)
    # Do stuff specific to Debian 6.0 codenamed Squeeze
    ;;
esac

This Bash script checks the type of the underlying operating systems and then does some stuff specific to it. The implicit assumption of this script is, that it will run on two operating systems only:

  • Ubuntu 12.04 codenamed Precise Pangolin and
  • Debian 6.0 codenamed Squeeze.

If it’s run on a different version, it will implicitly and wrongly assume that it’s running on Debian 6.0 codenamed Squeeze and will probably break things in ways that you haven’t ever imagined.

Furthermore it assumes that /bin/sh is Bash and it’ll probably throw an error on systems that link /bin/sh to a different shell like the Z shell (zsh), that is if the script uses syntax or features specific to Bash.

Explicit Bash Script

#!/bin/bash

operating_system=$(lsb_release -sc)

case $operating_system in
  precise)
    # Do stuff specific to Ubuntu 12.04 codenamed Precise Pangolin
    ;;
  squeeze)
    # Do stuff specific to Debian 6.0 codenamed Squeeze
    ;;
  *)
    echo "Don't know how to handle operating system ${operating_system}!"
    exit 1
    ;;
esac

This more explicit version of the same script explicitly checks for the two supported operating systems an outputs a message otherwise. A system administrator using this script on an unsupported system for the first time will find out easily where to look for an error.

Furthermore it explicitly uses /bin/bash making sure that it’ll work well on systems using a different shell as /bin/sh.

Conclusion

Carefully avoid implicit assumptions in your code as they will make it fail in obscure ways as soon as conditions change.

Comments