Asynchronous code...
- Executes in parallel to other code
- Uses a pattern such as Future
- Requires special language syntax
- Improves program performance
Click to show the answer
2: Async code uses futures, sometimes also called by other names such as "tasks", or other patterns such as callbacks. However, it does not require parallelism and can be used even in languages without special syntax by composing futures manually. While it may improve performance in some cases, it is mainly about maintainability and keeping the rest of the system reactive.
Canceling an asynchronous operation...
- Requires deleting the thread executing it
- Helps avoid unnecessary work
- Should always be done after a timeout
- Can only be done shortly after starting it
Click to show the answer
2: Cancellation can help avoid unnecessary work, regardless of what stage the operation is in. It should not require dealing with low-level concepts such as threads. Whether it should be done at all depends on context.
Testing async code...
- Involves
sleep
calls to wait for the result - Should generally not be done
- Is generally not a priority
- Can involve tests being async themselves
Click to show the answer
4: Testing async code can be done with async tests if the test framework supports it, but this is not required.
Async code is no different than other kinds of code in terms of prioritization of testing.
Never use sleep
to wait for an operation to finish in the background, this is brittle and slow!
A function should be async...
- If its current implementation uses asynchrony
- If it is likely to be implemented in an asynchronous way
- Unless there is a reason to choose otherwise
- If it helps maintain consistency with related functions
Click to show the answer
2 & 4: If it is part of a set of functions that are overall likely to use asynchrony, such as dealing with I/O, a function is probably better off as async, even if it is possible to implement it synchronously.
Viewing asynchrony as a monad...
- Is required in functional programming languages
- Helps understand asynchrony using existing concepts
- Means existing code can be reused without changes
- Requires an extra layer of indirection
Click to show the answer
3: Using existing concepts makes it easier to both understand async code, though this does not mean code that deals with other monads can or should be reused for async. This does not require a functional programming language nor more indirection.