Comment

Comment by combatentropy

All of the examples are far better than the code I normally deal with.

That being said, the most tiresome code is this kind of step-by-step error checking.

  if (! is_numeric($id)) {
    exit('The ID is not a number.');
  }

  $db = open_database();
  if (! $db) {
     exit('There was an error connecting to the database.');
  }

  $query = db_query($db, 'select * from widgets where id = $1', $id);
  if (! $query) {
     $db_error = get_db_error_msg($db);
     exit('There was something wrong with the query: ' . $db_error);
  }
Zzzzzzz. It triples the code size. One third is the normal code path. Two thirds is all the error checking. I'm sorry, I just don't write it:

  $db = open_database();
  $query = db_query($db, 'select * from widgets where id = $1', $id);
I let errors bubble up to some general error handler, which stops the script in its tracks and gives the user a vague and unhelpful error message. It doesn't matter. Even if I gave them a very specific error message, all that they would do is log a ticket, and I would still go into the server log to uncover the line number the error was on, debug, and fix it.

Don't get me wrong. I write JavaScript to constrain user input, with friendly directions and error messages. And I set tight types in the database and add database constraints where I can. But I don't write all this step-by-step checking in the middle layer (PHP, Python, Go, what have you). So if the user somehow bypasses the JavaScript and tries to insert text into an integer column, the database will simply refuse, and the resulting web page will be a very ugly error message, which is what they deserve.

If the database is down, it's going to be ugly, regardless.

I admit that this strategy works okay for non-life-threatening, SQL-backed web apps and such. You may need to do something tighter in your work. But I wonder if there would still be something more elegant than the every-other-line error checking shown in the article.

Discussion

Live from the official Hacker News API

A modern reader for Hacker News · SvelteKit + Skeleton