DEV Community

Jonathan
Jonathan

Posted on

2 2

Types vs. assertions

Types are build-time guarantees, assertions are run-time guarantees.

Do we software developers perhaps emphasise the former a little too much and the latter not quite enough?

One way assertions could help is:

Better error messages

Quite often an API call will return some value which we weren't expecting. It will fail with a cryptic message, e.g. about some value not being a valid number. And a mile-long stack trace. It's difficult and annoying to debug these errors.

Imagine if we added an assertion, which would run on the API response, and would report a more developer-friendly error message.

E.g.:

function assertEmployeeIdIsNumber(id: string) {
  if (!isNaN(id)) {
    throw new Exception(
      `Employee id '${id}' is not a valid number."
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

Now we can much more quickly & easily pinpoint where in the code this error happened, why it happened, which Backend endpoint caused it and how it could be fixed.

What do you think?

Image of Datadog

Master Mobile Monitoring for iOS Apps

Monitor your app’s health with real-time insights into crash-free rates, start times, and more. Optimize performance and prevent user churn by addressing critical issues like app hangs, and ANRs. Learn how to keep your iOS app running smoothly across all devices by downloading this eBook.

Get The eBook

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs