Aspect Oriented Programming

Aspect Oriented Programming Tutorial (Part-3)

Posted on Updated on

Hello All.

hope that everything is going best in your life.

This is a third part of my tutorial on topic of Aspect Oriented Programming … its too late .. i know … a month or more!! … second part was posted  i think 35 40 days back … and after that i got too much busy in some projects … plus my notebook had some problem with display hardware. Though i have composed this part many days back but final draft wasn’t compliled till today …. the thread of black berry application tutorial is also waiting for next part … seems i’m too much lazy …

Anyhow.. here are some more concepts regarding AOP. Due to shortage of time i will not include programing example today … the next part will cover all previous theory with practical examples … today just grasp few more concepts …

In this part, you will know some of basic terms/concepts that are core of AOP. You have to keep these things in considerations while building your application with AOP. let have a look over them …

Aspects

in very black-box definition, aspects in AOP are like classes in OOP. we put all the code that has scattered across the application in single unit call aspect, or in other words we express cross-cutting concerns in stand-alone modules called aspect (first benefit of AOP that it collects all scattered or tangled code across the application in form of cross cutting concerns and put them in separate units). For example, as we discussed in last part, logging code can cross-cut many modules, yet the aspect of logging should be separate from the functional concerns of the module where logging code was written. Aspects are similar to classes in their declaration, and they define types, just as classes do. In addition to its declaration, aspects contains both point-cuts and advice. We will define these two concerns in next sections.

Joint Points

A join point could be any point in the flow of your program. As name depicts this is a point in our application or source code where our program and aspect meet each other. or in other worlds, this is the point where AOP play its role. Join points represent well-defined points in a program’s execution that could be any method/constructor calls, method/constructor execution, field get and set, exception handler execution and/or static and dynamic initialization. You told your compiler via joint points that at this point inject the code from aspects and make final executable program.

Advices

Advices holds those piece of codes that actually executes when AOP play its role in our program. It may contain code that scattered across the application. Advice is a piece of code that we inject in our program when a join point is reached. You define advice relative to a point-cut like advices can executes before, after, or around a join point. It is an additional code that runs along with execution of our running program.

Again talk about logging.It is a concern that cross cut across the application, means same code for logging can be found in various modules of application. To understand the concept of advices, just think that we first define joint points in our application where we need logging. it means we find those methods where same logging code is present. secondly we put all logging code (infact same piece of code) in separate pieces of code called “advice” and then while compilation of our program, compiler inject advice’s code when its join point is reached. By doing that we picked all occurrence of same piece of code and put it in separate entity.

Don’t be confuse between advice and aspect. To understand the difference just think aspect like class and advice as any method in that class. got it …. !!!!

Point cut

Simply a pointcut is a set of join points. Whenever the program execution reaches one of the join points described in the pointcut, a piece of code associated with the pointcut (called advice) is executed. This allows a programmer to describe where and when additional code should be executed in addition to an already defined behavior. This permits the addition of aspects to existing software.

Introduction

I love this feature of AOP. Believe me if you get real soul of this, you will become fan of AOP, like i’m. Introduction allows aspects to modify the static structure of a program. By using introduction, aspects can add new methods and variables to a class, declare that a class implements an interface, or convert checked to unchecked exceptions. To understand what we can get by using Introductions, consider the following real life scenario.

In every institute, student has to pay their fee as monthly or semester basis. A student gets its fee slip form accounts branch and submits it in bank and get receipt. His/her  account file has been updated with copy of fee receipt. Thats looks fine in such scenario.

What if a student unable to submit his/her fee till dead line??? he/she has to submit a request form for granting him extension in fee submission or even for allowing him/her to submit his late fee.  In such case accounts branch will issue him an separate fee slip mentioning late fee fine. He/she will submit his late fee and will get fee receipt. In his record, few additional documents will be filed .i.e. application for allowing late fee, a late fee submission receipt, some other documents (like medical certificate etc) to prove why he/she was unable to submit fee within time.

In both cases, different kind of data was filed though the process was same .i.e. submitting fee.

Now let try to automate this scenario as a software module. You need to create a class having basic attributes related to fee like paymentDate, amount. The rest of the attribute that you need to track late fee submission will be stored in an aspect. Incase of any late fee case, the aspect will inject (or introduce) additional variable/methods into existing class so that you can store and retrieve information as per scenario. Remember that class structure will not change, just a new version or object will have some additional attribute. Hence different objects of same class may have different kind of attribute due to introduction feature of aspects.

Aspect Weaver

It weave our aspect and other business logic into single/final executable program. It works at compilation level of source code. How does it work is beyond the discussion of this tutorial. I will write a short note about its core functionality later on. Right now just think with AOP, we start by implementing our project using our OO language (for example, Java, or C++ ), and then we deal separately with crosscutting concerns in our code by implementing aspects. Finally, both the code and aspects are combined into a final executable form using an aspect weaver. As a result, a single aspect can contribute to the implementation of a number of methods, modules, or objects, increasing both reusability and maintainability of the code. We just define join-points, point-cuts, advices and aspects along with our business logic of program and then aspect weaver merge (infact weave) these things in our source code at compilation time.

in conventional way, our source code is simply compiled by language compiler and produce final executable code.

Aspect Weaver first weave your aspects, point-cuts, join-points, advices into our source code and make final script of code that will be ready to be compiled by language compiler, hence producing executable program containing our business logic along with AOP features.

free counters

Advertisements

Aspect Oriented Programming Tutorial :: Core Concept (Part-2)

Posted on Updated on

Hello All.
Hope that you all are doing best in all aspects of your life…

This is a second part of tutorial on aspect oriented programming. In last part, we discussed little about object oriented approach to design and develop computer based system and some issues with this approach. We talked about issues those are not concerned with a developer of specific module but he/she has to care those things, we saw a small chunk of code and realized that same lines of code are repeating in different classes/methods time and again and a developer has to write them even when those lines are not concerned with core logic of that method or developer’s expertise. aspect-modeling.org_browse_

In this part i will present aspect oriented approach to cope with such issues and to design/develop your application’s architecture with much better way. Again, may be my writing style, sentences structure, grammar, spells are not up to the mark, but it doesn’t matter, neither i’m going to tech you English nor it is an English literature class, so don’t worry 🙂 , i will try to focus on contents and concept so kindly accept my apology in advance.

Concern
orite, lets start … we know that every class, method or package in our software system has some responsibility in over all flow of application. Like some packages/classes for session management, some classes to obtain and mange database connections, some classes act like delegates, some work at middle layer to control transaction management etc … there are many other classes too that we develop as per user interface or to perform some other functionality. Anyone can guess the purpose of a class or method by just looking at its name (if good programming practices are in practice). Mean every class/method has something to concern with it, and in any application there are many possible concerns like managing role/permissions, fetching data as per specific criteria at specific screen, to control navigation, to handle session management and many others. So concern mean anything important that has to be done in software system. Any logic, any piece of code, or even a complete module.

Cross Cutting Concerns
While analyzing the user requirements and business scenarios in client’s world, you can analyze different concerns that you have to handle … and while you list down them you will realize that there are few things that are overlapping in each module or in different business scenario, or more precisely they span over different module or concerns. They present in all modules or help other modules to perform their concerning task properly. Such overlapping things or concerns are called cross-utting concerns. Means they cross cut different modules or concerns and present across the application in same form. In other words, These cross-cutting concers are pieces of logic that have to be applied at many places but actually don’t have anything to do with the core business logic of that particular class or method.

Issues with Cross Cutting Concerns
At this point I’m assuming that you have understand the term of concern and cross-cutting concerns. Again in short, concern is any functionality/logic/module/code that you have to implement to achieve some business goal; cross-cutting concerns are those concerns that are spread over the application and replicates in different concerns, got that!!! Good.

The biggest issues with cross cutting concerns are that they replicates in all applications, exists in different part of your code in more or less same form. Let consider the previous example again to clarify this point.

method Fetch_Employee_Data{

log start of method;
open data base session;

create query to fetch data;
log query and its parameters;
call to database to fetch data;
close database session;
log returned data from database;
log end of method;

return results;

}

Consider the above piece of code (in natural language). Last time we analyze that the bold lines can be found in every method of your application that fetch data from database, and wants to log different activities/interaction with database server. In any application, the logging and mechanism of interacting with database are major activities that have to perform again and again. In others words, logging and database interaction are two major concerns. Plus these concerns are also cross-cutting concerns because they are spreading across the application. In every method you can find them. You have no other option other than to write these lines of code in every method. What maximum you can do is to make separate classes and write all code there. Whenever you need logging and database interaction, just call methods of those classes. But again the problem is that you have to write call to those classes in every method; even a single line. This single line of code is much costly when you have to write them in every method of your class. One thing more, what if you need to have little change in that line? Again you have to edit/modify all those methods?

This thing become worst when a person that hasn’t concerned with such issue but he/she has to care about them. A person who has primary responsibility to write an optimal query to fetch data from database against a certain criteria but he/she is wasting his/her time in managing logging and database connectively issues. Is that fair? Absolutely not ..

The ideal solution for such issues is to identify and separate those piece of code/logic that span over the whole system, means their cross-cutting behavior or attribute should eliminate. Is there any way in OOP to do that? There isn’t unfortunately.

Aspect Oriented Programming Approach

No doubt Object-oriented programming (OOP) is a mainstream programming paradigm now a days. It provides software re-usability by providing design and language constructs for modularity, encapsulation, inheritance, and polymorphism. Though OOP has credit in implementing large scale projects and system, still it has some problems. It is practically proved that developers faces some problems in maintaining their code while working on large scale projects. An attempt to do a minor change in the program design may require several updates to a large number of unrelated modules. In other words, they have to change/update those modules that has no concern with core logic of required changes; more technically, they have to update many cross-cutting concerns at many places of code while doing a minor change in existing system. Hence OOP don’t have any concrete solution for managing and handling cross-cutting concerns in a software system. In object-oriented programming the natural unit of modularity is the class, and a cross-cutting concern is a concern that spans multiple classes (logging, context-sensitive error handling, performance optimization, and design patterns)

Aspect oriented approach provides solutions for such issues. It provides a way to design a software system architecture while considering the issue of cross-cutting concerns. It cleanly separate the cross-cutting concerns among different modules and treat them as autonomous construct hence remove their cross-cutting behavior.

To understand the core of AOP approach, again consider the previous example. If I remove the bold lines then remaining method will look like

method Fetch_Employee_Data{

create query to fetch data;
call to database to fetch data;
return results;

}

Here the developer hasn’t any worry about how connection with database is handling, how the logging happen. He just has to write those lines of code that belongs to core logic of that method. In other words, he is just concerned with core logic and doesn’t need to worry about other things. Doesn’t look good han??? AOP says that the class or method should perform only its concerned task and shouldn’t worry about other things. It provide a way to modularize different aspects of a system in least cohesive fashion.

How this happen? In AOP world, you pick all cross-cutting concern and develop them as separate entity, and when you need them in your code, just inject their functionality at run time. Looks strange?? i know at first glass it does. ok i try to clear by an example. Again consider the same example. In our Fetch_Employee_Data method we introduced logging to log all interaction with database server. We noticed that we have to write same line of code in every method. Now AOP says that pick these line of code, put them in separate entity, and wherever you need that logging functionality, just tell the compiler to inject logging in your method at your mentioned location; sounds good han …. it is indeed …. see you don’t need to write same code time and again in each method but only once in separate entity and compiler is injecting it in every method you mention. I will tell you latter how to write separate entity and how to tell compiler to inject at run time but right now just try to grasp core idea behind aspect oriented approach and how it is different from object oriented.

To me AOP is some kind of meta-programming. It complements object-oriented programming by facilitating another type of modularity that pulls together the widespread implementation of a cross-cutting concern into a single unit. These units are termed aspects, hence the name aspect-oriented programming. By compartmentalizing aspect code, cross-cutting concerns become easy to deal with. Aspects of a system can be changed, inserted or removed at compile time, and even reused. One thing to be noted is, that AOP does not replace OOP but adds certain decomposition features. I say it a nice add-on to OOP.

In next part i will tell you about major term used in aspect oriented programming. You learn how to pick cross-cutting concerns from system and write them as aspect; and how to tell compiler to inject them at run time. Till now i was talking in much generic fashion just to clear the concept, in next part i will discuss things pragmatically so be ready….

Aspect Oriented Programming (Part-1)

Posted on Updated on

Hello Everyone.

Hope you are doing best in all aspects of your life.

Today, I’m going to start new series of tutorials on new topic .i.e. Aspect Oriented Programming, in which you will learn about new programming aspectparadigm (though it’s too old), its basics, its core concept, comparison with current programming paradigms like Object Oriented Programming (OOA) and finally implementation for any real world problem or scenario.

Again, may be my writing style, sentences structure, grammar, spells are not up to the mark, but it isn’t an issue, i will try to focus on contents and concept so kindly accept my apology in advance.

I will post 3, 4 articles for this topic, dividing this in following possible sections

  • Object oriented programming approach and some flaws
  • Core theme of Aspect Oriented Programming
  • Solutions provided by AOP against OOP flaws
  • Important terms use in AOP talk
  • A programming example with OOP and AOP
  • Introduction of aspectJ, a java implementation of aspect oriented approach.

Object Oriented Programming Approach

Computer software or programs are an automation of real world scenarios, a transformation of manual work into computer operated systems. Many approaches are in practice to design and develop more usable, user friendly, easily evolevable and maintainable computer systems. Different approaches handles under-considerate domain with its own style. Object oriented approach focuses on data, takes anything in real world as data having some attributes (data fields) and some operations (methods). This approach evolves in sixth decade of last century when the computer system becomes much more complex and the current programming paradigms were not much capable to cope with required features to facilitate both developer and end users. At that moment researches were make on some new style of programming and then introduced “data focused” approach .i.e. object oriented programming where everything in real life was considered as object, in other words every noun is an object. We design systems based on these nouns in real world like Pay, Account, Employee, Product, PurchaseOrder, Invoice etc

Object oriented approach was at its peak in mid 80’s and late 90’s, even still a great number of computer systems are being developed using object oriented approach, but from its birth, it is facing many critics. Though the implementer of this approach are introducing many new features day by day in their respective languages compilers but only adding feature after feature into something don’t makes it better. Polymorphism, encapsulation, abstraction no doubt are building block of any mature programming language and should available implicitly, yet still there are few areas where developer need more ease and re-usability of their efforts and code. Those area were perceived and make researches and then new approach was presented to design and develop software module with more ease in re-usability of existing code, more ease in extendability and maintainability. This approach was AOP.

Did you ever feel that while development in object oriented world, you have you rewrite same chunk of code in different classes/methods to achieve a same goal? like (as a very simple example) in data access layer, you have to open database connection, maintain its session, writing query, call to database to fetch data and at the end, closing and the database connections and sessions. Like following

method Fetch_Employee_DATA{

open data base session;
create query to fetch data;
call to database to fetch data;
close database session;
return results;

}

here the bold text are those lines of code you have to write in each method you call to fetch data from database, other lines are method specific and depends upon the business logic.

As an other example, if you have to log each and every database call .i.e. the query to database, its parameter, the returned results etc, then you have to write same line of codes every time in each method that is going to interact with database. The above method will look like

method Fetch_Employee_DATA{

log start of method;
open data base session;
create query to fetch data;
log query and its parameters;
call to database to fetch data;
close database session;
log returned data from database;
log end of method;
return results;

}

Again the bold lines are those lines of code you are replicating in each method to achieve a same gaol. Don’t you think you’re spending a lot of time writing the same bits of code when it comes to implementing the individual methods. These things like logging, security checking, transaction management are such aspects of the systems that are orthogonal to the specific application. Every organization need them and every developer has to implement them in their respected module, classes and methods. In short the method hasn’t concern with these replicated lines, or the core concern of the method is to fetch employee, not to log database transactions, session maintenance etc. Every class or method is doing something extra time and again that doesn’t concern to their core requirement.

To small projects for small level organizations, it may work. But what if you are going to design and develop a banking system, an ERP for large scale company, or a payroll system for big industry … where the modules are interlink cohesively, the domain is very large, covering all business scenario of under-considerate organization. In such system, you can’t afford such framework and design that is difficult to extend, maintain and reuse. You can’t let your developers to spend time and resources over rewriting the same bit of code in every class and method, instead of focusing core business logic of that class. In other words, you can’t let everyone to focus on those things that are not concerned with their core task.

Consider the above example again. You are working in on a project (let suppose inventory management). While developing different features or modules, you have to call database to fetch and insert data as per business logic and domain requirement. We have seen that in every method you write, you are writing code of opening database session, and for closing it properly. In a medium and large scale project, the number of methods doing the same things could be hundreds. Any how, you complete your task and deploy the application at client site. Next time you are ask to maintain logs for each database interaction (as we discussed above) you instantly recall the number of classes and methods where you have to write code related to logging …. you have more then 40, 50 classes (let suppose) and there are hundreds of methods interacting with database. You have to open each method’s body and has to write logging code there ….

“Sir it will take atleast 4,5 days to complete this task”

“4, 5 days, but way, its really a simple task”

“indeed its simple but i have review each and every package, class and method to embed logging code there. To make sure the sustainability of application, i have to test it thoroughly to check that our existing application are new changes are running fine”

“hmmm ok, add someone else with you and try to complete it within 2,3 day, there are lot of other things too to do”

“sure i will”

This is the expected dialog between a developer and his manager/team lead while incorporation a simple change in running application. See, the actual lines that has to write in every method are very simple, just 2, 3 lines. But when it span over entire application with hundreds of packages/classes/methods then it becomes worst, consuming your more resources in term of human effort, time and budge.

Think again … is the logging concerned to method which was written to fetch data from database? Should a developer concern with database issues like opening a session and closing it properly who want to focus his attention to design an optimal query to fetch data from database?

In next post i will introduce Aspect Oriented Programming (AOP) and will discuss how AOP provides solutions for problems we discussed earlier.

Share on Facebook