Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add preconditional invariant checking #415

Merged
merged 9 commits into from
Jan 22, 2024
Merged

Conversation

vinceau
Copy link
Member

@vinceau vinceau commented Jan 20, 2024

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, and checkExists 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:

 public async sendVerificationEmail() {
   const auth = getAuth();
   const user = auth.currentUser;
-  if (!user) {
-    throw new Error("User is not logged in.");
-  }
+  Preconditions.checkExists(user, "User is not logged in.");
 
   if (!user.emailVerified) {
     log.info(`Sending email verification`);
     await sendEmailVerification(user);
   }
 }

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:

 async function fetchMediumNews(): Promise<NewsItem[]> {
   const response = await mediumJSONFeed("project-slippi");
-  if (response?.status !== 200) {
-    throw new Error("Error fetching Medium feed");
-  }
+  Preconditions.checkState(response?.status === 200, "Error fetching Medium feed");
 
   const result = response.response;
   // Do something with result
 }

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.

@vinceau vinceau merged commit 6f13b58 into main Jan 22, 2024
6 checks passed
@vinceau vinceau deleted the feat/precondition-checks branch January 22, 2024 07:40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant