Double-chance function

Source: Wikipedia, the free encyclopedia.

In

cross-platform
and scalable development.

Examples

Computer graphics

Consider a graphics

X11 graphics system, which can be ported to new graphics hardware by providing a very small number of device-dependent primitives, leaving higher level functions to a hardware-independent layer.[1][2]

The double-chance function is an optimal method of creating such an implementation, whereby the first draft of the port can use the "fast to market, slow to run" version with a common DrawPoint function, while later versions can be modified as "slow to market, fast to run". Where the double-chance pattern scores high is that the base API includes the self-supporting implementation given here as part of the null driver, and all other implementations are extensions of this. Consequently, the first port is, in fact, the first usable implementation.

One typical implementation in C++ could be:

 class CBaseGfxAPI {
     virtual void DrawPoint(int x, int y) = 0; /* Abstract concept for the null driver */
     virtual void DrawLine(int x1, int y1, int x2, int y2) { /* DrawPoint() repeated */}
     virtual void DrawSquare(int x1, int y1, int x2, int y2) { /* DrawLine() repeated */}
 };

 class COriginalGfxAPI : public CBaseGfxAPI {
     virtual void DrawPoint(int x, int y) { /* The only necessary native calls */ }
     virtual void DrawLine(int x1, int y1, int x2, int y2) { /* If this function exists a native DrawLine
                                                                routine will be used. Otherwise the base
                                                                implementation is run. */}
 };

 class CNewGfxAPI : public CBaseGfxAPI {
     virtual void DrawPoint(int x, int y) { /* The only necessary for native calls */ }
 };

Note that the CBaseGfxAPI::DrawPoint function is never used, per se, as any graphics call goes through one of its derived classes. So a call to CNewGfxAPI::DrawSquare would have its first chance to render a square by the CNewGfxAPI class. If no native implementation exists, then the base class is called, at which point the

native code
, if any is available.

With this method it is, theoretically, possible to build an entire 3D engine (applying software rasterizing) using only one native function in the form of DrawPoint, with other functions being implemented as and when time permits. In practice this would be hopelessly slow, but it does demonstrate the possibilities for double-chance functions.

References

  1. ^ Susan Angebranndt, Raymond Drewry, Philip Karlton, Todd Newman, "Definition of the Porting Layer for the X v11 Sample Server", MIT, 1988.
  2. ^ Susan Angebranndt, Raymond Drewry, Philip Karlton, Todd Newman, "Strategies for Porting the X v11 Sample Server", Mit 1988.
  • Goodwin, Steven (2005). Cross-Platform Game Programming. Charles River Media. .