Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I think the "if something bad happens throw an exception" thing does have some value, namely that you can make it very explicit in the code that this is a use case that you can't handle, and not that you merely forgot something or wrote a bug.

In PHP a pattern I often employ is:

  match ($value) {
    static::VALUE_1 => ..., 
    static::VALUE_2 => ..., 
    default => static::unreachable() 
  } 

Where unreachable is literally just:

  static function unreachable() { 
    throw new Exception('Unreachable'); 
  } 

Now, we don't actually need the default match arm. If we just leave it off entirely, and someone passes in something we can't match, it'll throw a PHP error about unmatched cases.

But what I've found is that if I do that, then other programmers go in later and just add in the case to the match statement so it runs. Which, of course, breaks other stuff down stream, because it's not a valid value we can actually use. Or worse: they add a default match arm that doesn't work! Just so the PHP interpreter doesn't complain.

But with this, now the reader knows "the person who wrote this considered what happens when something bad is passed in, and decided we cant handle it. There's probably a good reason for that". So they don't touch it.

Now, PHP has unique challenges because it's so dynamic. If someone passes in the wrong thing we might end up coercing null to zero and messing up calculations, or we might end up truncating a float or something. Ideally we prevent this with enums, but enums are a pain in the ass to write because of autoloading semantics (I don't want to write a whole new file for just a few cases)





Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: