Add check to avoid calling methods on undefined objects.  Prevents bugs
such as #174 and #266.