Double-chance function

In software engineering, a double-chance function is a software design pattern with a strong application in cross-platform and scalable development.

Examples

Computer graphics

Consider a graphics API with functions to DrawPoint, DrawLine, and DrawSquare. It is easy to see that DrawLine can be implemented solely in terms of DrawPoint, and DrawSquare can in turn be implemented through four calls to DrawLine. If you were porting this API to a new architecture you would have a choice: implement three different functions natively (taking more time to implement, but likely resulting in faster code), or write DrawPoint natively, and implement the others as described above using common, cross-platform, code. An important example of this approach is the 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 virtualization takes over and means that CNewGfxAPI::DrawLine is called. This gives the CNewGfxAPI class a “second chance” to use 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. ISBN 1-58450-379-3.

Read other articles:

The Royal Book of Oz, un'opera canonica nella serie di Oz, nonostante sia stata scritta nel 1921, dopo la morte dell'originale scrittore della serie L. Frank Baum nel 1919, dallo scrittore Ruth Plumly Thompson autorizzato da Reilly & Lee, l'editore originale[1] Il canone è, nel contesto della fiction, sia l'insieme di quei romanzi, storie, film, e simili che sono considerati come originali, cioè ufficiali, di un dato universo immaginario, sia l'insieme di quegli eventi, personag...

 

In this Chinese name, the family name is Chen. Chen Zi'ang陳子昂Chen Zi'ang, painted by Kanō Tsunenobu in the 18th century.Born661 or 656Shehong County, Sichuan, ChinaDied702 (aged 40–41)702 (aged 45–46)Shehong County, Sichuan, ChinaOccupation(s)Poet, politicianChinese nameTraditional Chinese陳子昂Simplified Chinese陈子昂TranscriptionsStandard MandarinHanyu PinyinChén Zĭ'ángWade–GilesCh‛en2 Tzŭ3-ang2IPA[ʈʂʰə̌n tsɹ̩̀.ǎŋ]Y...

 

Duta Besar Amerika Serikat untuk RusiaSegel Kementerian Dalam Negeri Amerika SerikatDicalonkan olehPresiden Amerika SerikatDitunjuk olehPresidendengan nasehat Senat Berikut ini adalah daftar Duta Besar Amerika Serikat untuk Rusia Daftar Nama Pickering, Thomas R.Thomas R. Pickering Collins, James FranklinJames Franklin Collins Vershbow, AlexanderAlexander Vershbow[1] Burns, William JosephWilliam Joseph Burns Beyrle, JohnJohn Beyrle McFaul, MichaelMichael McFaul Tefft, John FrancisJohn ...

Bartolomeo della GattaBiografiKelahiran1448 (Kalender Masehi Gregorius) Firenze Kematian1502 (Kalender Masehi Gregorius) (53/54 tahun)Arezzo KegiatanPekerjaanPelukis, illuminator (en) dan arsitek Ordo keagamaanCamaldolese Karya kreatifKarya terkenal(1482 (Kalender Masehi Gregorius)) Testament and Death of Moses (en) Bartolomeo della Gatta ‘The Annunciation’ oleh Bartolomeo della Gatta Bartolomeo della Gatta (1448-1502), lahir Pietro di Antonio Dei, adalah pelukis dan arsitek Italia. Ia ad...

 

Artikel ini sebatang kara, artinya tidak ada artikel lain yang memiliki pranala balik ke halaman ini.Bantulah menambah pranala ke artikel ini dari artikel yang berhubungan atau coba peralatan pencari pranala.Tag ini diberikan pada Desember 2023. Artikel atau sebagian dari artikel ini mungkin diterjemahkan dari List of accolades received by Philomena di en.wikipedia.org. Isinya masih belum akurat, karena bagian yang diterjemahkan masih perlu diperhalus dan disempurnakan. Jika Anda menguasai ba...

 

University in Thailand This article does not cite any sources. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: Sripatum University – news · newspapers · books · scholar · JSTOR (October 2019) (Learn how and when to remove this template message)Sripatum UniversityมหาวิทยาลัยศรีปทุมFormer nameThai Suriya CollegeTypePrivateEstablish...

[1] Cave and archaeological site in France Pech MerlePrehistoric cave artLocationLot Department, Midi-Pyrénées, FranceCoordinates44°30′27″N 1°38′40″E / 44.5074288°N 1.6443131°E / 44.5074288; 1.6443131 Pech Merle is a cave which opens onto a hillside at Cabrerets in the Lot département of the Occitania region in France, about 32 km by road east of Cahors. It is one of the few prehistoric cave painting sites in France that remain open to the g...

 

Stetoskop hitam dengan latar pelangi Topik LGBT dalam kedokteran adalah hal-hal yang berkaitan dengan masalah kesehatan masyarakat lesbian, gay, biseksual dan transgender dalam mengakses layanan-layanan kesehatan. Menurut Gay and Lesbian Medical Association (GLMA), disamping HIV/AIDS, masalah-masalah kesehatan LGBT yang meliputi penyakit-penyakit seperti orang pada umumnya seperti kanker payudara dan kaner serviks, hepatitis, kesehatan mental, penyalahgunaan obat-obatan, pemakaian tembakau, d...

 

Non-coding RNA molecule Small nucleolar RNA SNORD48Predicted secondary structure and sequence conservation of SNORD48IdentifiersSymbolSNORD48Alt. SymbolsU48RfamRF00282Other dataRNA typeGene; snRNA; snoRNA; C/D-boxDomain(s)EukaryotaGOGO:0006396 GO:0005730SOSO:0000593PDB structuresPDBe In molecular biology, SNORD48 (also known as U48) is a non-coding RNA (ncRNA) molecule which functions in the modification of other small nuclear RNAs (snRNAs). This type of modifying RNA is usually located in th...

Bambecquecomune Bambecque – Veduta LocalizzazioneStato Francia RegioneAlta Francia Dipartimento Nord ArrondissementDunkerque CantoneWormhout TerritorioCoordinate50°54′N 2°33′E / 50.9°N 2.55°E50.9; 2.55 (Bambecque)Coordinate: 50°54′N 2°33′E / 50.9°N 2.55°E50.9; 2.55 (Bambecque) Superficie11,78 km² Abitanti737[1] (2009) Densità62,56 ab./km² Altre informazioniCod. postale59470 Fuso orarioUTC+1 Codice INSEE59046 Carto...

 

Северный морской котик Самец Научная классификация Домен:ЭукариотыЦарство:ЖивотныеПодцарство:ЭуметазоиБез ранга:Двусторонне-симметричныеБез ранга:ВторичноротыеТип:ХордовыеПодтип:ПозвоночныеИнфратип:ЧелюстноротыеНадкласс:ЧетвероногиеКлада:АмниотыКлада:Синапси...

 

La Rappresentante di ListaLa Rappresentante di Lista nel 2021. Da sinistra: Veronica Lucchesi e Dario Mangiaracina Paese d'origine Italia GenerePop[1]Indie pop[2]Musica elettronica[3]Pop sperimentale[4] Periodo di attività musicale2011 – in attività EtichettaGarrincha Dischi (2014-2017)Woodworm (2017-presente) Album pubblicati6 Studio4 Live2 Sito ufficiale Modifica dati su Wikidata · Manuale La Rappresentante di Lista (noto anc...

ملخس   معلومات شخصية تاريخ الوفاة القرن 1 مشكلة صحية بتر[1][2]  الحياة العملية المهنة عامل منزلي  موظف في الكاهن الأعظم لبني إسرائيل[2]  تعديل مصدري - تعديل   ملخس أو ملخس العبد واسمه هو الصيغة اليونانية للاسم العبري «ملك» الذي معناه «مَلِك» وهو خادم رئ...

 

Skanstullsbron in July 2006. Skanstullsbron and Johanneshovsbron viewed from south-west in April 2006. Skanstullsbron (Swedish: The Fortlet Tollgate Bridge) is a bridge in central Stockholm, Sweden. Overpassing the older bridge Skansbron, it connects the major island Södermalm to the southern district Johanneshov. The first proposal for an elevated bridge stretching over the canal Hammarbykanalen was produced in 1921, before work on the lower Skansbron bridge began in 1923. It remained the f...

 

Movement to grant Puerto Rico U.S. statehood Politics of Puerto Rico Constitution and law United States Constitution Puerto Rico Constitution Puerto Rico law Executive Governor Cabinet Chief of Staff Executive departments Fiscal agent and financing Government-owned corporations Line of succession Office of the Governor Transition process First Lady Legislative Legislature: 17th Legislative Assembly of Puerto Rico Senate: 26th Senate of Puerto Rico President of the Senate: Thomas Rivera Schatz...

Mario Gomboli nel 2009 Mario Giuseppe Gomboli (Brescia, 18 luglio 1947) è un fumettista, sceneggiatore e illustratore italiano, noto soprattutto come soggettista e direttore responsabile, nonché editore, della serie Diabolik[1][2][3]. Biografia Nato a Brescia, quando è ancora bambino la famiglia si trasferisce a Milano dove, quando è studente al Liceo Scientifico Statale “Alessandro Volta”, conosce un compagno di classe, Alfredo Castelli, con il quale collabora...

 

Railway station in Kerala, India This article is about the railway station. For the town, see Kilikollur. For the City, see Kollam. KilikollurRegional rail, Light rail & Commuter rail stationKilikollur railway station buildingGeneral informationLocationNear NH-744, Kilikollur, Kollam, KeralaIndiaCoordinates8°55′04″N 76°37′57″E / 8.9179°N 76.6326°E / 8.9179; 76.6326Owned byIndian RailwaysOperated bySouthern Railway zoneLine(s)Kollam–Sengottai branch li...

 

From January to June, second of a trio Belgian Presidency of the Council of the European UnionLogo of the 2024 Belgian presidency1 January – 30 June 2024Council of the European UnionWebsitebelgium24.euPresidency trioSpainBelgiumHungary ← SpainHungary → Belgium currently holds the presidency of the Council of the European Union.[1][2][3][4] It is scheduled to hold a six-month term covering the first half of 2024.[1]&#...

Эту статью предлагается разделить на Глитч и Сбой.Пояснение причин и обсуждение — на странице Википедия:К разделению/28 ноября 2021. Возможно, она слишком велика или её содержимое не имеет логической связности, и предлагается разнести статью в Глитч и Сбой. Не удаляйте ша...

 

XM395 Precision Guided Mortar Munition prototype at Fort Benning, Ga., Feb 2006 [1] XM395 Precision Guided Mortar Munition (PGMM) adalah mortar 120 mm yang dikembangkan oleh Alliant Techsystems. Berdasarkan Orbital ATK’s Precision Guidance Kit untuk proyektil artileri 155 mm, XM395 menggabungkan panduan GPS dan permukaan kontrol terarah ke dalam paket yang menggantikan standar fuzzy, mengubah bodi mortir 120 mm yang ada menjadi amunisi berpandu presisi. Amunisi XM395 ...