Advice (programming)

In aspect and functional programming, advice describes a class of functions which modify other functions when the latter are run; it is a certain function, method or procedure that is to be applied at a given join point of a program.

Use

The practical use of advice functions is generally to modify or otherwise extend the behavior of functions which cannot or should not be readily modified or extended. For instance, the Emacspeak Emacs-addon makes extensive use of advice: it must modify thousands of existing Emacs modules and functions such that it can produce audio output for the blind corresponding to the visual presentation, but it would be infeasible to copy all of them and redefine them to produce audio output in addition to their normal outputs; so, the Emacspeak programmers define advice functions which run before and after.

For a simple Emacs example: suppose after a user corrected a mis-spelled word using the Emacs ispell module, they wanted to re-spellcheck the entire buffer. ispell-word offers no such functionality, even if the corrected word appears frequently in the buffer. The user could track down the definition of ispell-word, copy it into their personal Emacs files, and add the desired functionality there, but this is tedious and, worse, brittle (the user's version is now out of sync with the core Emacs implementation, if it even works without further refactoring). What the user wants is quite simple — just to run another command any time ispell-word runs. Using advice, it can be done as simply as this:

 (advice-add #'ispell-word
  :after #'flyspell-buffer)

While this example is obviously trivial, the strength of advice, especially when compared to similar facilities such as Python decorators and Java annotations, lies in the fact that not only do the advised functions / methods not need to be designed to accept advice, but also the advice themselves need not be designed to be usable as advice - they're just normal functions. The availability of evaluation throughout the lifetime of a piece of code (cf. code staging) in Lisp allows advice to be inlined automatically into any other code in a variety of ways. Any piece of code can be advised to carry out any other computation before, after, around, or instead of its original definition.

Readability

Advice has the potential to introduce confusion, as a piece of advice applied to a function is not apparent to a user who tracks down the function's source definition to learn about it. In such cases, advice acts almost like a COMEFROM, a joke facility added to INTERCAL to spoof the spaghettification attendant to the extensive use of GOTOs. In practice, however, such issues rarely present themselves. Upstream developers and maintainers of Lisp packages and modules never use advice, since there is no advantage to be gained by advising functions when their original source definitions can be freely rewritten to include the desired features. Advice is only useful in that it enables downstream users to subsequently modify default behaviour in a way that does not require propagation of such modifications into the core implementation's source definition.

Implementations

A form of advices were part of C with Classes in the late 1970s and early 1980s, namely functions called call and return defined in a class, which were called before (respectively, after) member functions of the class. However, these were dropped from C++.[1]

Advices are part of the Common Lisp Object System (CLOS), as :before, :after, and :around methods, which are combined with the primary method under "standard method combination".[2]

Common Lisp implementations provide advice functionality (in addition to the standard method combination for CLOS) as extensions. LispWorks[3] supports advising functions, macros and CLOS methods.

EmacsLisp added advice-related code in version 19.28, 1994.

History

The following is taken from a discussion at the mailing list aosd-discuss. Pascal Costanza contributed the following:

The term "advice" goes back to the term advising as introduced by Warren Teitelman in his PhD thesis in 1966. Here is a quote from Chapter 3 of his thesis:

Advising is the basic innovation in the model, and in the PILOT system. Advising consists of inserting new procedures at any or all of the entry or exit points to a particular procedure (or class of procedures). The procedures inserted are called "advice procedures" or simply "advice".
Since each piece of advice is itself a procedure, it has its own entries and exits. In particular, this means that the execution of advice can cause the procedure that it modifies to be bypassed completely, e.g., by specifying as an exit from the advice one of the exits from the original procedure; or the advice may change essential variables and continue with the computation so that the original procedure is executed, but with modified variables. Finally, the advice may not alter the execution or affect the original procedure at all, e.g., it may merely perform some additional computation such as printing a message or recording history. Since advice can be conditional, the decision as to what is to be done can depend on the results of the computation up to that point.
The principal advantage of advising is that the user need not be concerned about the details of the actual changes in his program, nor the internal representation of advice. He can treat the procedure to be advised as a unit, a single block, and make changes to it without concern for the particulars of this block. This may be contrasted with editing in which the programmer must be cognizant of the internal structure of the procedure.

"Advising" found its way into BBN Lisp and later into Xerox PARC's Interlisp.

It also found its way to Flavors, the first object-oriented extension to Lisp developed at MIT. They were subsumed under the notion of method combination.[4][a]

Since method combination and macros are closely related, it's also interesting to note that the first macro system was described in 1963, three years before Warren Teitelman's PhD thesis.[5][b]

See also

Notes

Gregor Kiczales comments the above as follows:

  1. ^ Advice appeared separately from Flavors in Maclisp and the Lisp Machine. You could advise any function, just like in Interlisp at the time. The before/after ontology appeared separately in Flavors methods.
  2. ^ Method combination and macros were only marginally related until much later, in New Flavors and CLOS, when a macro-like mechanism was provided to allow people to define their own rules for combining methods. Prior to that the rules governing combination of before/after methods and so-called whoppers methods (around) was fixed, and the compiler just generated the code for that. There were things called wrappers, which had macro-like behavior, but I forget when they came around. Traipsing through the various versions of MacLisp and Lispm manual to get this part of the history exactly right could be interesting. Or it could be that Howard Cannon or David Moon or someone could actually remember it all exactly.

References

  1. ^ The Design and Evolution of C++, p. 57
  2. ^ "A Brief Guide to CLOS". Archived from the original on 2015-05-06. Retrieved 2015-04-27.
  3. ^ LispWorks 7 User Guide and Reference Manual, The Advice Facility
  4. ^ See, for example, AIM-602 at https://web.archive.org/web/20060913001624/http://www.ai.mit.edu/research/publications/browse/0600browse.shtml
  5. ^ See AIM-57 at https://web.archive.org/web/20060913001624/http://www.ai.mit.edu/research/publications/browse/0000browse.shtml

Read other articles:

Batalyon Zeni Tempur 20/Pawbili Pelle AlangLambang Yonzipur 20/PPADibentuk11 Agustus 2020NegaraIndonesiaCabangZeniTipe unitSatuan Bantuan TempurPeranPasukan Prasarana MiliterBagian dariKodam XVIII/KasuariMarkasSorong, Papua Barat DayaJulukanYonzipur 20/PPAMotoPawbili Pelle AlangBaretHijauMaskotEnggang HitamUlang tahun2 FebruariPertempuranOperasi NemangkawiTokohKomandan saat iniLetkol Czi Moch. Zaenal Wafa, S.Sos. Batalyon Zeni Tempur 20/Pawbili Pelle Alang disingkat Yon Zipur 20/PPA sebelumny...

 

 

Kereta api IndocementKereta api Indocement berangkat dari Stasiun Madiun tujuan Kalimas, dan melintas tikungan timur Stasiun Madiun.IkhtisarJenisKereta api barangStatusBeroperasiLokasiDaerah Operasi I Jakarta (Nambo–Gedebage, Nambo-Kalimas, Nambo-Semarang Poncol, Nambo-Brambanan)Daerah Operasi III Cirebon (Arjawinangun-Brambanan dan Arjawinangun–Purwokerto)TerminusLihatlah dibawahLayanan3OperasiDibuka1964 (saat masih bernama Semen Jatimekar (1964-1984) dan Indocement (1984-2001, 2013-seka...

 

 

International Music Score Library Projectsito webLogo Pagina principale dell'IMSLP (gennaio 2016) URLpetruccilibrary.org/ Tipo di sitoBiblioteca musicale RegistrazioneOpzionale CommercialeNo ProprietarioProject Petrucci LLC Creato daEdward W. Guo Lancio16 febbraio 2006 Stato attualeIn progresso SloganSharing the world's public domain music. Modifica dati su Wikidata · Manuale L'International Music Score Library Project (IMSLP), o Petrucci Music Library (in italiano Biblioteca Musica...

2020 United States House of Representatives elections in Nebraska ← 2018 November 3, 2020 2022 → All 3 Nebraska seats to the United States House of Representatives   Majority party Minority party   Party Republican Democratic Last election 3 0 Seats won 3 0 Seat change Popular vote 585,234 326,018 Percentage 62.17% 34.63% Swing 0.14% 3.34% Election results by district Election results by county Republican   50–60%   60...

 

 

Pour les articles homonymes, voir Tension et Stress (homonymie). Le stress [stʁɛs] (de l'anglais stress [stɹɛs][1] Écouter) est, en biologie, l'ensemble des réactions d'un organisme soumis à des pressions ou contraintes de l'environnement, les stresseurs (en). Ces réactions dépendent toujours de la perception qu'a l'individu des pressions qu'il ressent. Selon la définition médicale, il s'agit d'une séquence complexe de situations provoquant des réactions phy...

 

 

Radio station in Escanaba, MichiganWYKXEscanaba, MichiganBroadcast area[1]Frequency104.7 MHzBrandingThe U.P.'s Country - Kix 104.7ProgrammingFormatCountryAffiliationsWestwood OneDetroit Lions Radio NetworkOwnershipOwnerTodd Mohr(Aurora Media, LLC)Sister stationsWDBCHistoryFirst air date1977Former call signsWFNN (?-1/31/83)Call sign meaningKiX CountryTechnical informationFacility ID35116ClassC1ERP100,000 wattsHAAT107 metersTranslator(s)103.9 W280GB (Escanaba)LinksWebsiteescanabaradiogroup...

محمد عزة دروزة محمد عزة دروزة في شبابه الأمين العام لحزب الاستقلال في المنصب1932 – 1947 المدير العام للأوقاف في فلسطين في المنصب1930 – 1937 معلومات شخصية اسم الولادة محمد عزة بن عبد الهادي دَرْوَزَة  الميلاد 21 يونيو 1888   نابلس  الوفاة 26 يوليو 1984 (96 سنة)   دمشق  مواطنة فل...

 

 

Film by Ridley Scott NapoleonTheatrical release posterDirected byRidley ScottWritten byDavid ScarpaProduced by Ridley Scott Kevin J. Walsh Mark Huffam Joaquin Phoenix Starring Joaquin Phoenix Vanessa Kirby CinematographyDariusz WolskiEdited by Claire Simpson Sam Restivo[1] Music byMartin Phipps[2]Productioncompanies Apple Original Films Scott Free Productions Distributed byColumbia Pictures (through Sony Pictures Releasing)Release dates November 14, 2023 (2023-1...

 

 

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

この記事は検証可能な参考文献や出典が全く示されていないか、不十分です。出典を追加して記事の信頼性向上にご協力ください。(このテンプレートの使い方)出典検索?: コルク – ニュース · 書籍 · スカラー · CiNii · J-STAGE · NDL · dlib.jp · ジャパンサーチ · TWL(2017年4月) コルクを打ち抜いて作った瓶の栓 コルク(木栓、�...

 

 

هذه المقالة يتيمة إذ تصل إليها مقالات أخرى قليلة جدًا. فضلًا، ساعد بإضافة وصلة إليها في مقالات متعلقة بها. (أبريل 2016) يفتقر محتوى هذه المقالة إلى الاستشهاد بمصادر. فضلاً، ساهم في تطوير هذه المقالة من خلال إضافة مصادر موثوق بها. أي معلومات غير موثقة يمكن التشكيك بها وإزالتها. ...

 

 

Season of television series Celebrity Big Brother 1Season 1Celebrity Big Brother 1 logoHosted byJulie ChenNo. of days26No. of houseguests11WinnerMarissa Jaret WinokurRunner-upRoss MathewsAmerica's Favorite HouseGuestRoss MathewsCompanion showCelebrity Big Brother: After Dark No. of episodes13ReleaseOriginal networkCBSOriginal releaseFebruary 7 (2018-02-07) –February 25, 2018 (2018-02-25)Additional informationFilming datesJanuary 31 (31-01) –February 25, 2018 ...

1937 film The CheatFrenchForfaiture Directed byMarcel L'HerbierWritten byJean-Georges AuriolJacques CompanéezHerbert JuttkeJacques NatansonHector TurnbullProduced byMichael SalkindPierre BraunbergerAyres d'AguiarRoger RichebéStarringVictor FrancenSessue HayakawaLouis JouvetCinematographyEugen SchüfftanEdited byPierre de HérainMarie Le BarsMusic byMichel MicheletProductioncompanySociété du Cinéma du PanthéonDistributed byGray-FilmRelease date 24 November 1937 (1937-11-24...

 

 

Asmara 2 Dunia Season 2Genre Drama Roman Fantasi Laga Misteri Ditulis olehTim Kreatif MKFSutradara Asep Khemunink Bobby Moeryawan Reza Fahlevi Pemeran Panji Saputra Andi Annisa Firstriana Aldila Arnold Leonard Brian Austin Isabelle Fry Charlotte Bellvania Ade Herlina Penggubah lagu temaAriel NoahLagu pembukaBintang di Surga oleh NoahLagu penutupBintang di Surga oleh NoahNegara asalIndonesiaBahasa asliBahasa IndonesiaJmlh. musim2Jmlh. episode7ProduksiProduser eksekutifSubagio S.Produser Sonu ...

 

 

此條目可参照英語維基百科相應條目来扩充。 (2021年4月27日)若您熟悉来源语言和主题,请协助参考外语维基百科扩充条目。请勿直接提交机械翻译,也不要翻译不可靠、低品质内容。依版权协议,译文需在编辑摘要注明来源,或于讨论页顶部标记{{Translated page}}标签。 此條目的引用需要清理,使其符合格式。 (2016年4月9日)参考文献应符合正确的引用、脚注及外部链接格式。 �...

索马里共和国过渡联邦政府Dowladda Federaalka Kumeelgaarka2004年—2012年 国旗 国徽 首都摩加迪沙常用语言索马里语 · 阿拉伯语政府临时政府总统 • 2004-2008 阿卜杜拉希·优素福·艾哈迈德 (首)• 2009-2012 谢里夫·艾哈迈德 (末) 历史时期索马里内战• 过渡宪章 2004年4月6日• 新政府 2012年8月20日 ISO 3166码SO 前身 继承 索马里过渡国家政府 索马里和解与重...

 

 

Australian dancer Evie FerrisFerris in 2022Background informationBorn (1997-02-18) 18 February 1997 (age 27)Cairns, AustraliaOccupation(s)Ballerina, singer, dancerYears active2007–presentMember ofThe WigglesMusical artist Evie Ferris (born 18 February 1997)[1] is an Australian ballerina and member of children's band The Wiggles.[2][3] Early life Ferris was born in Cairns, Australia,[4] and attended St Andrews Catholic College until year 7.[5] She...

 

 

Business school in Riga, Latvia BA School of Business and FinanceBanku AugstskolaFormer namesBanking CollegeTypePublic, self-financingEstablished1992RectorAndris SarnovičsAcademic staff48Administrative staff75Students1468[1]Undergraduates1145Postgraduates297Doctoral students26LocationRiga, Latvia56°58′32.17″N 24°8′5.87″E / 56.9756028°N 24.1349639°E / 56.9756028; 24.1349639Websitewww.ba.lv/en BA School of Business and Finance (Latvian: Banku Augstsk...

Para otros usos de este término, véase concierto (desambiguación). Concierto de música clásica. Un concierto es una expresión cultural musical en la «que se ejecutan composiciones sueltas».[1]​ En el ámbito de la música clásica occidental también es la forma musical en la que los materiales melódicos, rítmicos y armónicos se combinan en una composición, determinando así la cualidad sonora global de una pieza. Designa la forma de relacionarse las diversas voces que inte...

 

 

Renée de TeschenTitre de noblessePrincesseBiographieNaissance 2 janvier 1888PulaDécès 16 mai 1935 (à 47 ans)BaliceNationalité vénitienneFamille Habsbourg-LorrainePère Charles Étienne de TeschenMère Marie-Thérèse de Habsbourg-ToscaneFratrie Eléonore de TeschenCharles Albert de Habsbourg-AltenbourgMathilde de HabsbourgLéon Charles de Habsbourg-LorraineGuillaume François de Habsbourg-LorraineConjoint Jérôme Radziwill (à partir de 1909)Enfants Princess Maria-Teresa Radziwill...