Clouds
Home

Test Driven Development

Aspect Oriented Programming

Annotation Based Programming

Inversion Of Control - Part 1

Inversion Of Control - Part 2

Hibernate Interview Questions - Part 1

Hibernate Interview Questions - Part 2

Hibernate Interview Questions - Part 3

Spring Interview Questions

EJB 3.0 Interview Questions

Aspect Oriented Programming Interview Questions


What is aspect oriented programming (AOP) ? Do you have any experience with AOP ?

Aspect-Oriented Programming (AOP) complements OOP (Object Oriented Programming) by allowing the developer to dynamically modify the static OO model to create a system that can grow to meet new requirements. AOP allows you to dynamically modify your static model consisting mainly of business logic to include the code required to fulfill the secondary requirements or in AOP terminology called cross-cutting concerns (i.e. secondary requirements) like auditing, logging, security, exception handling etc without having to modify the original static model (in fact, we don't even need to have the original code). Better still, we can often keep this additional code in a single location rather than having to scatter it across the existing model, as we would have to if we were using OOP on its own.

For example:

A typical Web application will require a servlet to bind the HTTP request to an object and then pass it to the business handler object to be processed and finally return the response back to the user. So only a minimum amount of code is initially required. But once you start adding all the other additional secondary requirements or cross-cutting concerns like logging, auditing, security, exception-handling, transaction demarcation, etc the code will inflate to 2-4 times its original size. This is where AOP can assist by separately modularizing these cross-cutting concerns and integrating theses concerns at runtime or compile time through aspect weaving. AOP allows rapid development of an evolutionary prototype using OOP by focusing only on the business logic by omitting concerns such as security, auditing, logging etc. Once the prototype is accepted, additional concerns like security, logging, auditing etc can be weaved into the prototype code to transfer it into a production standard application.

AOP nomenclature is different from OOP and can be described as shown below:

Join points:

represents the point at which a cross-cutting concern like logging, auditing etc intersects with a main concern like the core business logic. Join points are locations in programsí execution path like method & constructor call, method & constructor execution, field access, class & object initialization, exception handling execution etc.

Pointcut:

is a language construct that identifies specific join points within the program. A pointcut defines a collection of join points and also provides a context for the join point.

Advice:

is an implementation of a cross-cutting concern which is a piece of code that is executed upon reaching a pointcut within a program.

Aspect:

encapsulates join points, pointcuts and advice into a reusable module for the cross-cutting concerns which is equivalent to Java classes for the core concerns in OOP. Classes and aspects are independent of one another. Classes are unaware of the presence of aspects, which is an important AOP concept. Only pointcut declaration binds classes and aspects.

Weaving

is the process for interleaving separate cross-cutting concerns such as logging into core concerns such as business logic code to complete the system. AOP weaving composes different implementations of aspects into a cohesive system based on weaving rules. The weaving process (aka injection of aspects into Java classes) can happen at:
  • Compile-time: Weaving occurs during compilation process.
  • Load-time: Weaving occurs at the byte-code level at class loading time.
  • Runtime: Similar to load-time where weaving occurs at byte-code level during runtime as join points are reached in the executing application.
  • So which approach to use ?

    Load-time and runtime weaving have the advantages of being highly dynamic and enabling changes on the fly without having to rebuild and redeploy. But Load-time and runtime weaving adversely affect system performance. Compile time weaving offers better performance but requires rebuilding and redeployment to effect changes.

    Do you have any experience with AOP ?

    Two of the most interesting modules of the Spring framework are AOP (Aspect Oriented Programming) and Inversion Of Control (IoC) container (aka Dependency Injection). Let us look at a simple AOP example.

    STEP 1:

    Define the interface and the implementation classes. Spring promotes the code to interface design concept.

    public interface Hello {
    public void hello();
    }
    public class HelloImpl implements Hello{
    public void hello() {
    System.out.println("Printing hello. ");
    }
    }

    STEP 2:

    Configure the Spring runtime via the SpringConfig.xml file. Beans can be configured and subsequently injected into the calling Test class.

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/springbeans.dtd">
    <beans>
    <!-- bean configuration which enables dependency injection -->
    <bean id="helloBean" class="org.springframework.aop.framework.ProxyFactoryBean">
    <property name="target">
    <bean class="HelloImpl" singleton="false" />
    </property>
    </bean>
    </beans>

    STEP 3:

    Write your Test class. The "SpringConfig.xml" configuration file should be in the classpath.

    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.FileSystemXmlApplicationContext;
    public class Test {
    public static void main(String[] args) {
    ApplicationContext ctx = new FileSystemXmlApplicationContext("SpringConfig.xml");
    Hello h = (Hello)ctx.getBean("helloBean");
    h.hello();
    }
    }


    If you run the Test class, you should get an output of :

    Printing hello.

    Now, if you want to trace your methods like hello() before and after in your Hello class, then you can make use of the Spring AOP.

    STEP 4:

    Firstly you need to define the classes for the before and after advice for the method tracing as follows:

    import java.lang.reflect.Method;
    import org.springframework.aop.MethodBeforeAdvice;
    public class TracingBeforeAdvice implements MethodBeforeAdvice {
    public void before(Method arg0, Object[] arg1, Object arg2) throws Throwable {
    System.out.println("Just before method call...");
    }
    }


    import java.lang.reflect.Method;
    import org.springframework.aop.AfterReturningAdvice;
    public class TracingAfterAdvice implements AfterReturningAdvice {
    public void afterReturning(Object arg0, Method arg1, Object[] arg2, Object arg3) throws Throwable {
    System.out.println("Just after returning from the method call...");
    }
    }

    STEP 5:

    In order to attach the advice to the appropriate joint points, you must make a few amendments to the SpringConfig.xml file as shown below in bold:

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/springbeans.dtd">
    <beans>
    <!-- bean configuration which enables dependency injection -->
    <bean id="helloBean" class="org.springframework.aop.framework.ProxyFactoryBean">
    <property name="target">
    <bean class="HelloImpl" singleton="false" />
    </property>
    <property name="interceptorNames">
    <list>
    <value>traceBeforeAdvisor
    <value>traceAfterAdvisor
    </list>
    </property>
    </bean>
    <!-- Advice classes -->
    <bean id="tracingBeforeAdvice" class="TracingBeforeAdvice" />
    <bean id="tracingAfterAdvice" class="TracingAfterAdvice" />
    <!-- Advisor: way to associate advice beans with pointcuts -->
    <!-- pointcut definition for before method call advice -->
    <bean id="traceBeforeAdvisor" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">
    <property name="advice">
    <ref local="tracingBeforeAdvice" />
    </property>
    <property name="pattern">
    <!-- apply the advice to Hello class methods -->
    <value>Hello.*
    </property>
    </bean>
    <!-- Advisor: way to associate advice beans with pointcuts -->
    <!-- pointcut definition for after returning from the method advice -->
    <bean id="traceAfterAdvisor" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">
    <property name="advice">
    <ref local="tracingAfterAdvice" />
    </property>
    <!-- apply the advice to Hello class methods -->
    <property name="pattern">
    <value>Hello.*
    </property>
    </bean>
    </beans>


    If you run the Test class again, you should get an output with AOP in action:

    Just before method call...
    Printing hello.
    Just after returning from the method call...


    Spring offers declarative transaction management. This is enabled by Spring AOP. Declarative transaction management should be preferred over programmatic transaction management since it is non-invasive and has least impact on your application code. Not only transaction management but also other system level services like security, logging, auditing etc should be implemented declaratively with the AOP feature.

    What are the differences between OOP and AOP ?

    Object Oriented Programming (OOP)

  • OOP looks at an application as a set of collaborating objects. OOP code scatters system level code like logging, security etc with the business logic code.
  • OOP nomenclature has classes, objects, interfaces etc.
  • Provides benefits such as code reuse, flexibility, improved maintainability, modular architecture, reduced development time etc with the help of polymorphism, inheritance and encapsulation.

    Aspect Oriented Programming (AOP)

  • AOP looks at the complex software system as combined implementation of multiple concerns like business logic, data persistence, logging, security, multithread safety, error handling, and so on. Separates business logic code from the system level code. In fact one concern remains unaware of other concerns.
  • AOP nomenclature has join points, point cuts, advice, and aspects.
  • AOP implementation coexists with the OOP by choosing OOP as the base language. For example: AspectJ uses Java as the base language.
  • AOP provides benefits provided by OOP plus some additional benefits which are discussed in the next question.

    What are the benefits of AOP ?

  • OOP can cause the system level code like logging, transaction management, security etc to scatter throughout the business logic. AOP helps overcome this problem by centralizing these cross-cutting concerns.
  • AOP addresses each aspect separately in a modular fashion with minimal coupling and duplication of code. This modular approach also promotes code reuse by using a business logic concern with a separate logger aspect.
  • It is also easier to add newer functionalities by adding new aspects and weaving rules and subsequently regenerating the final code. This ability to add newer functionality as separate aspects enable application designers to delay or defer some design decisions without the dilemma of over designing the application.
  • Promotes rapid development of evolutionary prototypes using OOP by focusing only on the business logic by omitting cross-cutting concerns such as security, auditing, logging etc. Once the prototype is accepted, additional concerns like security, logging, auditing etc can be weaved into the prototype code to transfer it into a production standard application.
  • Developers can concentrate on one aspect at a time rather than having to think simultaneously about business logic, security, logging, performance, multithread safety etc. Different aspects can be developed by different developers based on their key strengths. For example: A security aspect can be developed by a security expert or a senior developer who understands security.

    Annotation Based Programming Interview Questions>>>




    Home Clouds