Direct style
In computer programming, direct style is the usual style of sequential programming, in which control is passed implicitly by simply going to the next line, by subroutine calls, or by constructs such as return
, yield
, or await
. It is contrasted with continuation-passing style, in which control is passed explicitly in the form of a continuation. Direct style programming is widely viewed as easier to write and understand than continuation-passing style, and thus a number of programming language constructs exist to eliminate or minimize the need to explicitly use continuations.
In mainstream languages continuation-passing style primarily occurs by passing closures as callbacks (function arguments), and thus direct style more simply means that functions return a value, rather than taking a function argument.[1]
Programming constructs
Programming constructs that enable direct style programming include coroutines, which in turn can implement generators and futures, all of which enable a direct style.[2][3]
Example
For example, in Dart, an animation loop may be written in the following way:[4]
- Continuation-passing style
var running = true; // Set to false to stop.
tick(time) {
context.clearRect(0, 0, 500, 500);
context.fillRect(time % 450, 20, 50, 50);
if (running) window.animationFrame.then(tick);
}
window.animationFrame.then(tick);
In CPS, the asynchronous call window.animationFrame
waits for the next frame, then calls the callback, which requires a callback function and a tail call.
- Direct style
var running = true; // Set to false to stop.
while (running) {
var time = await window.animationFrame;
context.clearRect(0, 0, 500, 500);
context.fillRect(time % 450, 20, 50, 50);
}
In direct style, the asynchronous call window.animationFrame
simply yields control, then continues, and while loop can be used instead of a callback.
References
- ↑ "Composing Synchronous and Asynchronous Functions in JavaScript".
- ↑ "Javascript's Future: Generators". October 5, 2012.
- ↑ "SIP-22 - Async", "The main purpose of async/await is to make it possible to express efficient asynchronous code in a familiar direct style (where suspending operations look as if they were blocking). As a result, non-blocking code using Scala’s futures API [1] can be expressed without using higher-order functions, such as map and flatMap, or low-level callbacks."
- ↑ Gilad Bracha (October 2014). "Dart Language Asynchrony Support: Phase 1".