משתמש:Yoavtz/תכנות מונחה היבטים
דף זה אינו ערך אנציקלופדי
| ||
דף זה אינו ערך אנציקלופדי | |
תכנות מונחה היבטים (תכנות מוכוון היבטים, תכנות מונחה אספקטים, באנגלית Aspect-Oriented Programming, AOP) היא פרדיגמה תכנותית שמטרתה להשיג מודולריות על-ידי הפרדה וכימוס של עניינים צולבים החותכים לרוחב מבנה התכנה.
סקירה
[עריכת קוד מקור | עריכה]תכנות מונחה היבטים עוסק בחלוקה של לוקיגת התכנה לחלקים שונים (חלקי פונקציונליות קשורים ואחידים, המוכנים עניינים). כמעט כל פרדיגמות התכנות מאפשרות קיבוץ וכימוס של עניינים לישויות נפרדות ועצמאיות על-ידי הפשטות (כדוגמת שגרות, [[מודול (תוכנה)|מודולים] ומחלקות) אשר משמשים למימוש, להפשטה ולהרכבה של עניינים אלה. אולם, עניינים מסוימים נוגדים מטבעם מימוש מרוכז, והם נקראים עניינים צולבים (או עניינים חותכים) משום שהם עוסקים בחתך רוחבי של חלקי התכנה.
רישום (logging) הוא דוגמא לעניין צולב משום שמדיניות רישום מטבעה עוסקת בכל חלקי התכנה. רישום חותך את כל המודולים באופן רוחבי.
מימושים של פרדיגמת התכנות מונחה ההיבטים מספקים ביטויים צולבים אשר מאגדים ומכמסים כל עניין במקום אחד. המימושים השונים נבדלים בכוח, בבטיחות ובשמישות של המבנים שהם מספקים. למשל, מיירטים (interceptors) המפרטים את שיטת היירוט מספקים אופן מוגבל של חיתוך, ללא תמיכה בבטיחות-טיפוסים או בניפוי שגיאות. המימוש AspectJ מכיל ביטויים כאלה ומאגד אותם במחלקה מיוחד הנקראת היבט (aspect). היבט יכול לשנות את התנהגותו של קוד על-ידי עצות (advice) המופעלות בנקודות חיבור (join points) בתכנה. השאילתא הבוחרת את נקודות החיתוך עליהן פועל ההיבט נקראת חתך-נקודות (pointcut).
היסטוריה
[עריכת קוד מקור | עריכה]תכנות מונחה היבטים צמח ממספר אבות ישירים: [1] Reflection ופרוטוקולי מטה-עצמים (metaobject protocols), תכנות מונחה נושאים, מסנני הרכבה (composition filters) ותכנות אדפטיבי.[2] גרגור קיצאלס Gregor Kiczales ועמיתיו בXerox PARC פיתחו את עקרון התכנות מונחה ההיבטים, וכן מימשו את ההרחבה AspectJ של Java. צוות הפיתוח של IBM העדיפו כלים על שפה חדשה, ובשנת 2001 הציעו את Hyper/J ואת Concern Manipulation Environment, אשר לא מצאו שימוש רב. ל-EmacsLisp נוספה תמיכה בתכנות מונחה היבטים בגרסה 19.28. הדוגמאות במאמר זה משתמשות ב-AspectJ משום שהיא הנפוצה והמוכרת ביותר.[דרוש מקור]
Microsoft Transaction Server נחשב ליישום המשמעותי הראשון של תכנות מונחה עצמים, ואחריו הגיע Enterprise JavaBean.[3][4]
מוטיבציה ומושגים בסיסיים
[עריכת קוד מקור | עריכה]לרוב, היבט מפוזר או שזור בקוד, ולפיכך קשה להבנה ולתחזוקה. הפיזור נובע מאופיו הפונקציונלי המפוזר בין חלקים בלתי קשורים של מערכת או חלקי מערכת תכנה. בדוגמת הרישום (logging), בכדי לשנות מדיניות רישום עשוי להדרש שינוי של כל חלקי הקוד המושפעים. בנוסף, היבטים נשזרים לא רק בפונקציונלית העיקרית של מערכת אלא גם אחד בשני, ולכן שינוי של עניין אחד כרוך בהבנה של כל העניינים השזורים, או לפחות של המנגנון המטפל בהם.
נקח לדוגמא יישום בנקאות עם שיטה פשוטה להעברת סכום כסם מחשבון אחד לאחר:[5]
void transfer(Account fromAcc, Account toAcc, int amount) throws Exception {
if (fromAcc.getBalance() < amount) {
throw new InsufficientFundsException();
}
fromAcc.withdraw(amount);
toAcc.deposit(amount);
}
מתודה פשוטה זו מתעלמת ממספר שיקולים שעשויים להיות נוכחים ביישום אמיתי: היא חסרה בדיקות אבטחה כדי לוודא שהמשתמש רשאי לבצע פעולת העברה; עליה להיות עטופה בטרנזקציית בסיס-נתונים כדי למנוע אובדן מידע; על הפעולה להרשם ביומן אירועים, וכד'.
גרסה המכילה את כל אלה עשוייה להראות כך:
void transfer(Account fromAcc, Account toAcc, int amount, User user, Logger logger)
throws Exception {
logger.info("Transferring money...");
if (! checkUserPermission(user)){
logger.info("User has no permission.");
throw new UnauthorizedUserException();
}
if (fromAcc.getBalance() < amount) {
logger.info("Insufficient funds, sorry.");
throw new InsufficientFundsException();
}
fromAcc.withdraw(amount);
toAcc.deposit(amount);
//get database connection
//save transactions
logger.info("Successful transaction.");
}
בדוגמה עניינים שונים נשזרו בפונקציונליות הבסיסית (לעתים מכונה העניין העיקרי). טרנזקציות, אבטחה ורישום הם דוגמאות נפוצות לעניינים צולבים. במצב התכנית הנוכחי, כאשר נצטרך לשנות את מדיניות האבטחה של היישום, יהיה עלינו לדאוג לקוד המפוזר במספר רב של מתודות.
תכנות מונחה היבטים שואף לפתור בכך שהוא מאפשר למתכנת לתאר עניינים צולבים במודולים עצמאיים המכונים היבטים aspects. היבטים מכילים עצות advice (קוד המצורף לנקודות מסוימות בתכנית) והגדרות בין-טיפוסיות inter-type declarations (מידע מבני המצורף למחלקות אחרות). לדוגמא, מודול אבטחה עשוי לכלול עצה המודאת את השראותיו של משתמש לפני שהוא ניגש לחשבון בנק כלשהו. חיתוך-הנקודות pointcut מגדיר את המקומות בקוד, המכונות נקודות חיבור join points, בהן עשוי משתמש לנסות לגשת לחשבון בנק, בעוד הקוד בגוף העצה ממומשת בדיקת האבטחה עצמה. כך, הן הבדיקה והן המקומות עליהם היא מופעלת מוגדים ומתוחזקים במקום אחד. בנוסף, חיתוך-נקודות מוצלח יתפוס שינויים עתידיים בתכנה כך שמתודות חדשות הניגשות לחשבונות בנק יתייעצו בעצה ולא יתעלמו מבדיקות האבטחה.
נממש רישום כהיבט בדוגמא שלמעלה:
aspect Logger {
void Bank.transfer(Account fromAcc, Account toAcc, int amount, User user, Logger logger) {
logger.info("Transferring money...");
}
void Bank.getMoneyBack(User user, int transactionId, Logger logger) {
logger.info("User requested money back.");
}
// other crosscutting code...
}
מודלים של נקודות חיבור
[עריכת קוד מקור | עריכה]רכיב העצה בשפה מונחית היבטים מגדיר מודל של נקודות חיבור (Join-Point Model, JPM). מודל כזה מגדיר שלושה דברים:
- מתי מורצות העצות. נקודות אתה נקראות נקודות חיבור משום שהן נקודות בתכנית בהן ניתן לחבר התנהגות נוספת. כדי להיות שימושית, נקודת חיבור צריכה להיות קלה להבנה ולזיהוי על-ידי מתכנת רגיל. כמו-כן עליה להיות עמידה לשינויים בתכנית, כדי שההיבט יהיה יציב ועמיד בשינויים כאלה. ברוב המימושים של תכנות מונחה היבטים, מתודות ופניות לשדות נתמכים כנקודות חיבור.
- דרך לאסוף או לציין נקודות חיבור, הנקראת חיתוך-נקודות pointcut. חיתוכי-נקודות בוחרים תת-קבוצה מנקודות החיבור האפשרויות. בשפות רבות חיתוך הנקודות מוגדר בתחביר דומה לזה של שפת-הבסיס, למשל AspectJ מגדירה אותן בצורה המזכירה חתימות פונקציות ב-Java.
- דרך לקשור קוד לנקודות חיבור. בAspectJ עצות יכולות לרוץ לפני, אחרי או במקום מתודות.
מודלים של נקודות חיבור נבדלים בנקודות החיבור האפשריות, בדרך בה הן נבחרות, בפעולות שאפשר לקשור לנקודות החיבור ובשיפורים המבניים שניתן לבטא בעזרתם.
מודל נקודות החיבור ב-AspectJ
[עריכת קוד מקור | עריכה]- נקודות החיבור ב-AspectJ כוללות ריצות של [[מתודה (תכנות)|מתודות] ובנאים, אתחול של מחלקה או של אובייקט, קריאה או כתיבה של שדה, טיפול בחריגות וכו'. הן אינן כוללות לולאות, קריאות למימושים של מחלקות האב, ומשפטים מסוימים (כמו משפטי זריקת חריגה).
- חיתוכי-נקודות מוגדרים על-ידי צירוף
- Pointcuts are specified by combinations of primitive pointcut designators (PCDs).
- "Kinded" PCDs match a particular kind of join point (e.g., method execution) and tend to take as input a Java-like signature. One such pointcut looks like this:
execution(* set*(*))
- This pointcut matches a method-execution join point, if the method name starts with "
set
" and there is exactly one argument of any type.
"Dynamic" PCDs check runtime types and bind variables. For example
this(Point)
- This pointcut matches when the currently executing object is an instance of class
Point
. Note that the unqualified name of a class can be used via Java's normal type lookup.
"Scope" PCDs limit the lexical scope of the join point. For example:
within(com.company.*)
- This pointcut matches any join point in any type in the
com.company
package. The*
is one form of the wildcards that can be used to match many things with one signature.
Pointcuts can be composed and named for reuse. For example
pointcut set() : execution(* set*(*) ) && this(Point) && within(com.company.*);
- This pointcut matches a method-execution join point, if the method name starts with "
set
" andthis
is an instance of typePoint
in thecom.company
package. It can be referred to using the name "set()
".
- Advice specifies to run at (before, after, or around) a join point (specified with a pointcut) certain code (specified like code in a method). The AOP runtime invokes Advice automatically when the pointcut matches the join point. For example:
after() : set() { Display.update(); }
- This effectively specifies: "if the
set()
pointcut matches the join point, run the codeDisplay.update()
after the join point completes."
Other potential join point models
[עריכת קוד מקור | עריכה]There are other kinds of JPMs. All advice languages can be defined in terms of their JPM. For example, a hypothetical aspect language for UML may have the following JPM:
- Join points are all model elements.
- Pointcuts are some boolean expression combining the model elements.
- The means of affect at these points are a visualization of all the matched join points.
Inter-type declarations
[עריכת קוד מקור | עריכה]Inter-type declarations provide a way to express crosscutting concerns affecting the structure of modules. Also known as open classes, this enables programmers to declare in one place members or parents of another class, typically in order to combine all the code related to a concern in one aspect. For example, if a programmer implemented the crosscutting display-update concern using visitors instead, an inter-type declaration using the visitor pattern might look like this in AspectJ:
aspect DisplayUpdate {
void Point.acceptVisitor(Visitor v) {
v.visit(this);
}
// other crosscutting code...
}
This code snippet adds the acceptVisitor
method to the Point
class.
It is a requirement that any structural additions be compatible with the original class, so that clients of the existing class continue to operate, unless the AOP implementation can expect to control all clients at all times.
Implementation
[עריכת קוד מקור | עריכה]AOP programs can affect other programs in two different ways, depending on the underlying languages and environments:
- a combined program is produced, valid in the original language and indistinguishable from an ordinary program to the ultimate interpreter
- the ultimate interpreter or environment is updated to understand and implement AOP features.
The difficulty of changing environments means most implementations produce compatible combination programs through a process known as weaving - a special case of program transformation. An aspect weaver reads the aspect-oriented code and generates appropriate object-oriented code with the aspects integrated. The same AOP language can be implemented through a variety of weaving methods, so the semantics of a language should never be understood in terms of the weaving implementation. Only the speed of an implementation and its ease of deployment are affected by which method of combination is used.
Systems can implement source-level weaving using preprocessors (as C++ was implemented originally in CFront) that require access to program source files. However, Java's well-defined binary form enables bytecode weavers to work with any Java program in .class-file form. Bytecode weavers can be deployed during the build process or, if the weave model is per-class, during class loading. AspectJ started with source-level weaving in 2001, delivered a per-class bytecode weaver in 2002, and offered advanced load-time support after the integration of AspectWerkz in 2005.
Any solution that combines programs at runtime has to provide views that segregate them properly to maintain the programmer's segregated model. Java's bytecode support for multiple source files enables any debugger to step through a properly woven .class file in a source editor. However, some third-party decompilers cannot process woven code because they expect code produced by Javac rather than all supported bytecode forms (see also "Problems", below).
Deploy-time weaving offers another approach.[6] This basically implies post-processing, but rather than patching the generated code, this weaving approach subclasses existing classes so that the modifications are introduced by method-overriding. The existing classes remain untouched, even at runtime, and all existing tools (debuggers, profilers, etc.) can be used during development. A similar approach has already proven itself in the implementation of many Java EE application servers, such as IBM's WebSphere.
Terminology
[עריכת קוד מקור | עריכה]Standard terminology used in Aspect-oriented programming may include:
- Cross-cutting concerns
- Even though most classes in an OO model will perform a single, specific function, they often share common, secondary requirements with other classes. For example, we may want to add logging to classes within the data-access layer and also to classes in the UI layer whenever a thread enters or exits a method. Even though each class has a very different primary functionality, the code needed to perform the secondary functionality is often identical.
- Advice
- This is the additional code that you want to apply to your existing model. In our example, this is the logging code that we want to apply whenever the thread enters or exits a method.
- Pointcut
- This is the term given to the point of execution in the application at which cross-cutting concern needs to be applied. In our example, a pointcut is reached when the thread enters a method, and another pointcut is reached when the thread exits the method.
- Aspect
- The combination of the pointcut and the advice is termed an aspect. In the example above, we add a logging aspect to our application by defining a pointcut and giving the correct advice.
Comparison to other programming paradigms
[עריכת קוד מקור | עריכה]Aspects emerged out of object-oriented programming and computational reflection. AOP languages have functionality similar to, but more restricted than metaobject protocols. Aspects relate closely to programming concepts like subjects, mixins, and delegation. Other ways to use aspect-oriented programming paradigms include Composition Filters and the hyperslices approach. Since at least the 1970s, developers have been using forms of interception and dispatch-patching that resemble some of the implementation methods for AOP, but these never had the semantics that the crosscutting specifications provide written in one place.
Designers have considered alternative ways to achieve separation of code, such as C#'s partial types, but such approaches lack a quantification mechanism that allows reaching several join points of the code with one declarative statement.
Adoption issues
[עריכת קוד מקור | עריכה]Programmers need to be able to read code and understand what is happening in order to prevent errors.[7] Even with proper education, understanding crosscutting concerns can be difficult without proper support for visualizing both static structure and the dynamic flow of a program. Beginning in 2002, AspectJ began to provide IDE plug-ins to support the visualizing of crosscutting concerns. Those features, as well as aspect code assist and refactoring are now common.
Given the power of AOP, if a programmer makes a logical mistake in expressing crosscutting, it can lead to widespread program failure. Conversely, another programmer may change the join points in a program – e.g., by renaming or moving methods – in ways that the aspect writer did not anticipate, with unintended consequences. One advantage of modularizing crosscutting concerns is enabling one programmer to affect the entire system easily; as a result, such problems present as a conflict over responsibility between two or more developers for a given failure. However, the solution for these problems can be much easier in the presence of AOP, since only the aspect needs to be changed, whereas the corresponding problems without AOP can be much more spread out.
Implementations
[עריכת קוד מקור | עריכה]The following programming languages have implemented AOP, within the language, or as an external library:
- .NET Framework languages (C# / VB.NET)[8]
- ActionScript[9]
- Ada[10]
- AutoHotkey[11]
- C / C++[12]
- COBOL[13]
- The Cocoa Objective-C frameworks[14]
- ColdFusion[15]
- Common Lisp[16]
- Delphi[17][18][19]
- Delphi Prism[20]
- e (IEEE 1647)
- Emacs Lisp[21]
- Groovy
- Haskell[22]
- Java[23]
- JavaScript[24]
- Logtalk[25]
- Lua[26]
- make[27]
- ML[28]
- PHP[29]
- Racket[30]
- Perl[31]
- Prolog[32]
- Python[33]
- Ruby[34][35][36]
- Squeak Smalltalk[37][38]
- UML 2.0[39]
- XML[40]
See also
[עריכת קוד מקור | עריכה]- Aspect-oriented software development
- Distributed AOP
- Attribute grammar, a formalism that can be used for aspect-oriented programming on top of functional programming languages
- Programming paradigms
- Stability Model
- Subject-oriented programming, an alternative to Aspect-oriented programming
- Executable UML
- COMEFROM: Some elements of aspect-oriented programming have been compared to the joke COMEFROM statement.[41]
הערות שוליים
[עריכת קוד מקור | עריכה]- ^ "Aspect-Oriented Programming" "Kiczales, G.; Lamping, J; Mehdhekar, A; Maeda, C; Lopes, C. V.; Loingtier, J; Irwin, J. Proceedings of the European Conference on Object-Oriented Programming (ECOOP), Springer-Verlag LNCS 1241. June 1997."
- ^ "Adaptive Object Oriented Programming: The Demeter Approach with Propagation Patterns" Karl Liebherr 1996. ISBN 0-534-94602-X מציג גרסה מעובדת של אותו הנושא (Lieberherr הכיר בכך מאוחר יותר והתאים את גישתו).
- ^ Don Box; Chris Sells (4 בנובמבר 2002). Essential.NET: The common language runtime. Addison-Wesley Professional. p. 206. ISBN 978-0-201-73411-9. נבדק ב-4 באוקטובר 2011.
{{cite book}}
: (עזרה) - ^ Roman, Ed; Sriganesh, Rima Patel; Brose, Gerald (1 בינואר 2005). Mastering Enterprise JavaBeans. John Wiley and Sons. p. 285. ISBN 978-0-7645-8492-3. נבדק ב-4 באוקטובר 2011.
{{cite book}}
: (עזרה) - ^ שים לב: הדוגמאות במאמר זה מופיעות בתחסיר המזכיר תחביר של שפת Java.
- ^ http://www.forum2.org/tal/AspectJ2EE.pdf
- ^ Edsger Dijkstra, Notes on Structured Programming, pg. 1-2
- ^ Numerous: Afterthought, LOOM.NET, Enterprise Library 3.0 Policy Injection Application Block, AspectDNG, Aspect#, Compose*, PostSharp, Seasar.NET, DotSpect (.SPECT), Spring.NET (as part of its functionality), Wicca and Phx.Morph, SetPoint
- ^ as3-commons-bytecode
- ^ Ada2012 Rationale
- ^ Function Hooks
- ^ Several: AspectC++, XWeaver project, FeatureC++, AspectC, AspeCt-oriented C, Aspicere
- ^ Cobble
- ^ AspectCocoa
- ^ ColdSpring
- ^ AspectL
- ^ InfraAspect
- ^ MeAOP in MeSDK
- ^ DSharp
- ^ RemObjects Cirrus
- ^ Emacs Advice Functions
- ^ monad (functional programming),Monads As a theoretical basis for AOP, and Aspect-oriented programming with type classes.
- ^ Numerous others: CaesarJ, Compose*, Dynaop, JAC, Google Guice (as part of its functionality), Javassist, JAsCo (and AWED), JAML, JBoss AOP, LogicAJ, Object Teams, PROSE, The AspectBench Compiler for AspectJ (abc), Spring framework (as part of its functionality), Seasar, The JMangler Project, InjectJ, GluonJ, Steamloom
- ^ Many: Advisable, Ajaxpect, jQuery AOP Plugin, Aspectes, AspectJS, Cerny.js, Dojo Toolkit, Humax Web Framework, Joose, Prototype - Prototype Function#wrap, YUI 3 (Y.Do)
- ^ Using built-in support for categories (which allows the encapsulation of aspect code) and event-driven programming (which allows the definition of before and after event handlers).
- ^ AspectLua
- ^ MAKAO
- ^ AspectML
- ^ Several: PHPaspect, Aspect-Oriented PHP, Seasar.PHP, PHP-AOP, FLOW3
- ^ AspectScheme
- ^ The Aspect Module
- ^ "Whirl"
- ^ Several: PEAK, Aspyct AOP, Lightweight Python AOP, Logilab's aspect module, Pythius, Spring Python's AOP module, Pytilities' AOP module
- ^ AspectR
- ^ AspectR-Fork
- ^ Aquarium
- ^ AspectS
- ^ MetaclassTalk
- ^ WEAVR
- ^ AspectXML
- ^ C2:ComeFrom
Further reading
[עריכת קוד מקור | עריכה]- Kiczales, Gregor; John Lamping; Anurag Mendhekar; Chris Maeda; Cristina Lopes; Jean-Marc Loingtier; John Irwin (1997). "Aspect-Oriented Programming". Proceedings of the European Conference on Object-Oriented Programming, vol.1241. pp. 220–242. The paper generally considered to be the authoritative reference for AOP.
- Holzinger, Andreas; M. Brugger; W. Slany (2011). Applying Aspect Oriented Programming (AOP) in Usability Engineering processes: On the example of Tracking Usage Information for Remote Usability Testing. In: Marca, D. A., Shishkov, B. & Sinderen, M. v. (Eds.) Proceedings of the 8th International Conference on electronic Business and Telecommunications. Sevilla, 53-56.
- Filman, Robert E.; Tzilla Elrad; Siobhán Clarke; Mehmet Aksit (2004). Aspect-Oriented Software Development. ISBN 0-321-21976-7.
- Pawlak, Renaud; Lionel Seinturier; Jean-Philippe Retaillé (2005). Foundations of AOP for J2EE Development. ISBN 1-59059-507-6.
- Laddad, Ramnivas (2003). AspectJ in Action: Practical Aspect-Oriented Programming. ISBN 1-930110-93-6.
- Jacobson, Ivar; Pan-Wei Ng (2005). Aspect-Oriented Software Development with Use Cases. ISBN 0-321-26888-1.
- Aspect-oriented Software Development and PHP, Dmitry Sheiko, 2006
- Clarke, Siobhán; Elisa Baniassad (2005). Aspect-Oriented Analysis and Design: The Theme Approach. ISBN 0-321-24674-8.
- Yedduladoddi, Raghu (2009). Aspect Oriented Software Development: An Approach to Composing UML Design Models. ISBN 3-639-12084-1.
- "Adaptive Object-Oriented Programming Using Graph-Based Customization" – Lieberherr, Silva-Lepe, et al. - 1994
External links
[עריכת קוד מקור | עריכה]- Eric Bodden's list of AOP tools in .net framework
- Programming Styles: Procedural, OOP, and AOP
- Programming Forum: Procedural, OOP, and AOP
- Aspect-Oriented Software Development, annual conference on AOP
- AOSD Wiki, Wiki on aspect-oriented software development
- AspectJ Programming Guide
- The AspectBench Compiler for AspectJ, another Java implementation
- Series of IBM developerWorks articles on AOP
- A detailed series of articles on basics of aspect-oriented programming and AspectJ
- What is Aspect-Oriented Programming?, introduction with RemObjects Taco
- Constraint-Specification Aspect Weaver
- Aspect- vs. Object-Oriented Programming: Which Technique, When?
- Gregor Kiczales, Professor of Computer Science, explaining AOP, video 57 min.
- Aspect Oriented Programming in COBOL
- Aspect-Oriented Programming in Java with Spring Framework
- Wiki dedicated to AOP methods on.NET
- Early Aspects for Business Process Modeling (An Aspect Oriented Language for BPMN)
- AOSD Graduate Course at Bilkent University
- Introduction to AOP - Software Engineering Radio Podcast Episode 106
- An Objective-C implementation of AOP by Szilveszter Molnar
- Apect-Oriented programming for iOS and OS X by Manuel Gebele