Difference between revisions of "Precondition and Assertion Best Practices"

From Coder Merlin
(Add page with First Draft. Quiz, Code snippets, and Glossary to be added)
 
(→‎Quiz: finish quiz)
Line 44: Line 44:


==== Quiz ====
==== Quiz ====
<quiz shuffle=none display=simple>
{
What is the primary difference between an Assertion and a Precondition?
|type="()"}
- Preconditions assume that an Assertion will fail
- Assertions can print a message whereas Preconditions can't
+ Assertions should not be used in production while Preconditions should be used in debugging and production
- Preconditions and Assertions are the same
{
What is a sanity check's purpose?
|type="[]"}
- To provide checking for correct syntax
+ To allow a developer to check a feature they think should be true
- To check a complex portion of code where the developer is entirely unsure what the output may be
+ To provide checking for correct logic
{
Why are Assertions better than if-statements for debugging?
|type="[]"}
+ Assertions document in the code explicitly that something unexpected has happened as opposed to an if-statement that indicates the outcome was expected
- An if-statement will require that a function or method be invoked instead of stopping the program
+ Assertions can be ignored automatically when the application goes into a production build
- Assertions and if-statements are the same and can be used interchangeably
{
What is the main benefit of using Assertions?
|type="[]"}
+ To find erroneous outputs in parts of code
- To prevent corruption when going into production
- To optimize code so that it may have higher performance by ignoring areas of logic
+ To maintain logic throughout a program that is assumed to be true
{
In what scenario would an Assertion or AssertionFailure be used?
|type="[]"}
+ To test the output of a function follows the logic that was expected
+ To stop the execution of a program for attempting to do something that was assumed impossible
- To override user input or internal logic within a program if given unusable data
- To stop execution of a program before files start to be corrupted
{
What's the benefit of a Precondition?
|type="[]"}
- To fix syntax errors before they cause errors during execution
+ To find areas where code may not practically move forward during debugging
+ Preconditions can be used during production to prevent errors
- Provide a way to stop a program in production at any point
{
In what scenario would a Precondition or PreconditionFailure be used?
|type="[]"}
+ To use prior to a function or method that requires certain data or variables to be set a certain way
- To use as a last resort following a severe error in a program to prevent file corruption
- To address an area of code where it is assumed necessary conditions will not be present
+ To use during an area of code that should not have been able to execute meaning preconditions have failed
{
Why is the usage of Assertion and Precondition a best practice?
|type="[]"}
- Using these features allows a developer to anticipate errors linked to their logic and address them
- Using these features allows a developer to address the errors in logic they have found in their code
+ Using these features allows a developer to maintain logic
+ Using these features allows a developer to dynamically debug their code
{
True or False: Both Assertions and Preconditions stop executing a give program if they fail
|type="()"}
+ True
- False
True or False: A Failed Assertion does not mean the program must stop executing
|type="()"}
+ True
- False
</quiz>

Revision as of 08:39, 18 December 2021

Within these castle walls be forged Mavens of Computer Science ...
— Merlin, The Coder

Overview[edit]

In Swift, an important debugging feature one must know is the usage of Assertions and Preconditions. In brief, these are tools in Swift that allow a developer to assert that certain aspects of a program are true or declare a precondition before executing the rest of a given program. The following will provide an explanation of how to use these features, why they should be used liberally, and where a developer may want to implement them.

Usage[edit]

To start, let's quickly examine these functions to better understand their purpose. To start, understand that this article will look at the following four methods: Assert(), Precondition(), AssertionFailure(), and PreconditionFailure().

Assert is found in many other languages such as C, it's used to perform what are called sanity-checks. Essentially, these are for areas of code where a developer wants to confirm relatively simple parts of a program that are assumed to be true. An assertion takes a boolean as its first parameter, the developer assumes that this boolean will evaluate to true. However, if the assertion was not true, the program will stop executing and "crash." These Assertions are meant to be used solely in a Testing/Debugging stage.

AssertionFailure is similar to Assert, however it lacks any boolean parameter. This means Assertion Failure will always result in the app crashing. This function is meant to be used for when the program failed something that it shouldn't have, thus the app will crash. But as with assert, assertionFailure is meant to be used for Debugging environments.

Precondition, on the other hand, can be used in both production and debugging environments. It works almost the same as Assertions in this regard. The use case of a precondition is that there must be this condition that evaluates to true or else the program can not practically continue. Since assertions may be false but wouldn't necessarily mean the program has to stop executing, assertions are simply ignored during production but a precondition means that the application must stop executing whether it be in Production or a Testing environment.

PreconditionFailure is essentially the precondition counter part to AssertionFailure. These are used for when a Precondition has failed and therefore lacks a boolean parameter. This is because if the program has gotten to the point where it's attempting to execute this line of code, something has gone wrong and the application must stop running. As with Precondition, this function can be used in production.

Benefits[edit]

In the world of software, there's a term called Defensive programming. It means ensuring that a program will continue to function under unforeseen circumstances. The tools just outlined are a phenomenal way of ensuring this. Let's examine the benefits both Assertions and Preconditions provide to a developer.

Assertions[edit]

To start, there is the quintessential feature of an Assertion, that they are ignored for production. This is incredibly valuable as it allows a developer to write in a series of assertions, perform the necessary sanity checks during debugging, and not have to worry about these checks affecting the production build. This is far superior than simply using an if-statement because not only will the developer have to go back and manually delete these if-statements before the program can be used in an actual application but also an if-statement makes the assumption that the error that is being tested for is expected to happen and that there is a handling of this error in the code.

Instead, Assertions allow a developer to perform many checks for an application to ensure that the program does not have any logic-errors. A logic error simply refers to when the developer has faulty logic when trying to execute a program such as if a function doesn't return the desired output. Observe the following for several instances oh how assertions should be used.

Assertion Examples[edit]

Preconditions[edit]

Preconditions provide an invaluable tool to defensively program. By using this feature, a developer can say that it does not expect a certain scenario to happen, but if it were to, stop running. Of course, in a production build this will be less than ideal as it means the application has crashed while being used, but during testing, if a precondition is thrown, it allows a programmer to find these potentially critical errors and address them before being shipped to an end user.

However, even if the precondition had to be activated during a production build, it will still provide benefits to the user as the program will simply terminate meaning the codebase and data are safe guarded from any corruption or vulnerabilities that could come up from having preconditions that are not met.

In this way, by liberally using Preconditions and Assertions together, a developer is able to find any possible mistakes in logic, both small and critical, and address these bugs before they affect user experience as well as provide safeguards if issues arise during production.

Observe the following for examples on how to use Preconditions in an application.

Precondition Examples[edit]

Conclusion[edit]

All in all, these tools prove to be a significantly more efficient way of debugging an application as opposed to a rudimentary if-statement. By using these tools, an application can be significantly improved by providing a dynamic testing routine, ensuring that assumptions made hold true, that the logic employed holds true, and that the preconditions that are essential to the function of the program are present.

Quiz[edit]

Syntax error

1 What is the primary difference between an Assertion and a Precondition?

Preconditions assume that an Assertion will fail
Assertions can print a message whereas Preconditions can't
Assertions should not be used in production while Preconditions should be used in debugging and production
Preconditions and Assertions are the same

2 What is a sanity check's purpose?

To provide checking for correct syntax
To allow a developer to check a feature they think should be true
To check a complex portion of code where the developer is entirely unsure what the output may be
To provide checking for correct logic

3 Why are Assertions better than if-statements for debugging?

Assertions document in the code explicitly that something unexpected has happened as opposed to an if-statement that indicates the outcome was expected
An if-statement will require that a function or method be invoked instead of stopping the program
Assertions can be ignored automatically when the application goes into a production build
Assertions and if-statements are the same and can be used interchangeably

4 What is the main benefit of using Assertions?

To find erroneous outputs in parts of code
To prevent corruption when going into production
To optimize code so that it may have higher performance by ignoring areas of logic
To maintain logic throughout a program that is assumed to be true

5 In what scenario would an Assertion or AssertionFailure be used?

To test the output of a function follows the logic that was expected
To stop the execution of a program for attempting to do something that was assumed impossible
To override user input or internal logic within a program if given unusable data
To stop execution of a program before files start to be corrupted

6 What's the benefit of a Precondition?

To fix syntax errors before they cause errors during execution
To find areas where code may not practically move forward during debugging
Preconditions can be used during production to prevent errors
Provide a way to stop a program in production at any point

7 In what scenario would a Precondition or PreconditionFailure be used?

To use prior to a function or method that requires certain data or variables to be set a certain way
To use as a last resort following a severe error in a program to prevent file corruption
To address an area of code where it is assumed necessary conditions will not be present
To use during an area of code that should not have been able to execute meaning preconditions have failed

8 Why is the usage of Assertion and Precondition a best practice?

Using these features allows a developer to anticipate errors linked to their logic and address them
Using these features allows a developer to address the errors in logic they have found in their code
Using these features allows a developer to maintain logic
Using these features allows a developer to dynamically debug their code

9 True or False: Both Assertions and Preconditions stop executing a give program if they fail

True
False
True
False