Add preconditional invariant checking #415
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Description
This PR adds a consistent method for enforcing an invariant to be true prior to some method logic. We introduce two functions
checkState
which asserts any condition to be true, andcheckExists
which checks that it is not null or undefined. These functions provide type safety for the remainder of the code block.Warning
These functions are not a replacement for error handling, rather it's to be used in cases where certain values or parameters must exist or be a certain value before executing the main logic.
Consider the following example:
This is a common case where we want to execute certain logic (in this case, send an email), but before we do that we want to check that the user currently exists. This is a case where we can rewrite it with a
Preconditions.checkExists(user)
to make this easier to read.Now consider this anti-example:
It could be tempting to replace the conditional error with a
Preconditions.checkState(response?.status === 200)
however it's not really a condition that needs to be checked before the executing of core logic. This is simply error handling after we've fetched the data. Therefore we should not use a precondition check in this situation.