# Aspect-Oriented Programming Under .NET

Λογισμικό & κατασκευή λογ/κού

18 Νοε 2013 (πριν από 4 χρόνια και 5 μήνες)

120 εμφανίσεις

Aspect
-
Oriented Programming
Under .NET

Ramaswamy Krishnan
-
Chittur

Dr. James W. Fawcett

Contents

1.
Background

An example

2.
Introduction

-

How AOP works

3.
Aspects explored

-

We studied four areas of application

4.
Analysis

-

Comparison of metrics with and without

5.
Conclusion

-

How effective is AOP?

6.
Future work

7.
Summary

8.
Bibliography

-

30 references in Thesis

1. Background

Let us consider the following piece of code that calculates the area
of a sector, given the radius and angle:

public double

SectorArea (
double

double

angle)

{

return

}

Now, if we want to ensure that the code enables range check on its
parameters and on the return value, such that

The radius must be non negative.

The angle should be between 0 and 2 PI, and may be

The return value, i.e., the sector area, is a non
-
negative value

then, the code should be modified as follows:

1. Background

The code with the validation check for its parameters could be:

public double

SectorArea (
double

double

angle)

{

if

throw new

if

( (angle < 0.0) || (angle > 2 * 3.14) )

throw new

ArgumentOutOfRangeException ("angle out of range.");

double

if
(result < 0)

throw new

Exception (“Return value out of range.");

return

result;

}

Wouldn’t it be better if we can develop a code like the following snippet for
this purpose?

[
return
: Range (Lower = 0.0)]

public

double

SectorArea ([Range (Lower = 0.0)]
double

[Range (Lower = 0.0, Upper = 6.28)]
double

angle)

{

return

}

1.
Background

This (AOP
-
based) code has managed to remove the
if
-
then
-
else’s

from the application code.

The style is
Declarative

programming. We replaced imperative
code with a declaration of an attribute.

It is clear from the AOP
-
code that:

The
return value

has a lower bound of
0.0

The parameter

has a lower bound of
0.0

The parameter
angle

has to be between
0.0

and
2 times PI

If any of the parameters, or the return value go out of range, an
exception is raised with the necessary details which in turn, can be
handled appropriately by the client.

2.
Introduction

Improving management of large software systems

SP
-

Structured Programming
:

Decomposes large monolithic programs into modules using
functional decomposition

OOD
-

Object Oriented Design:

Associates data with functions allowed to act on that data, e.g.,
an object, proven to be an effective structuring tool.

COM
-

Component Object Model:

Reduces interdependencies between objects, using interfaces
and object factories for isolation.

AOP
-

Aspect Oriented Programming:

Separates program’s primary functionality from needed support
infrastructure to simplify a program’s logic.

2. Introduction
-

Aspects

In

the

early

1990
’s,

Gregor

Kiczales

et
.

al
.

published

a

seminal

paper

on

what

they

called

the

young

idea

of

Aspect

Oriented

Programming”

(AOP)

at

Proc
-
Europe

Conference

on

object
-
oriented

programming

In

commonly

employed

code,

there

are

elements

that

are

orthogonal

to

the

primary

functionality

of

the

code
.

These

elements,

though

extraneous

to

the

primary

purpose

of

the

code,

are

vital

to

its

proper

execution
.

Further

more,

they

tend

to

be

scattered

throughout

the

system

so

that

they

contribute

to

the

complexity

of

the

code
.

These

elements

are

called

aspects
.

Examples

of

aspects

include

processing

to

support

‘security’,

‘fault
-
tolerance’

and

‘synchronization’
.

2. Introduction

AOP

Aspect
-
oriented programming (AOP) isolates aspects
into separate modules so that the resulting client
-
code is

more purpose
-
specific,

more reusable, and

less complex.

The technique used in this thesis work for
implementing AOP is the
interception of method
calls
.

Interception is triggered by
declaring

attributes.

2.
AOP

How it works

2.
Introduction

Interception:

Technique for implementing AOP

2.
AOP application :
LAN Server

2. Remember the Range Checker Example?

The code with the validation check for its parameters could be:

public double

SectorArea (
double

double

angle)

{

if

throw new

if

( (angle < 0.0) || (angle > 2 * 3.14) )

throw new

ArgumentOutOfRangeException ("angle out of range.");

double

if
(result < 0)

throw new

Exception (“Return value out of range.");

return

result;

}

Wouldn’t it be better if we can develop a code like the following snippet for
this purpose?

[
return
: Range (Lower = 0.0)]

public

double

SectorArea ([Range (Lower = 0.0)]
double

[Range (Lower = 0.0, Upper = 6.28)]
double

angle)

{

return

}

2.
Analysis of Range Checker

Client code statistics:

AOP library statistics:

Non
-
AOP

AOP

Lines

of

function

code

20

3

Cyclomatic

complexity

11

3

Cohesion

6

AOP library
: Developed
ONCE

Client code
: application
-
specific

Aspect

code

Interception
code

Lines

of

function

code

137

67

Cyclomatic

complexity

26

7

2. Analysis of Range Checker

payoff

AOP reduces the complexity of the application code:

less

if
-
then
-
elses in the client code.

AOP captures the purpose of the code better:

[Range (Lower = 0.0)]
double

at the function declaration is more explicit and more readable than

if

throw new

ArgumentOutOfRangeException (“...");

in the body of the function.

AOP enhances abstraction and encapsulation:

The validation check is isolated as a separate module. Any change to validation check
handling can be made at this
ONE

place.

AOP promotes reusability:

The range
-
checker attribute provides a common point where the out
-
of
-
range exceptions can
be handled.

The range
-
checker can be applied to a variety of classes which need range
-
checks.

2. But
----

We have to exert
significant effort

to set up
an attribute.

If we choose wisely the targets for AOP,
where there are many opportunities to use
them, then:

We simply declare attributes every place we
need the service.

We don’t need to repeatedly write code to
supply the service.

2.
Research Goals

1.
To identify several applications where the aspect
-
oriented
approach can be applied.

Aspects that are dealt with in this thesis work are:

1.
Method
-
Synchronization,

2.
Debugging,

3.
Code
-
Profiling,

4.
Prioritization,

5.
Validation.

2.
To evaluate the impacts of AOP on code complexity and
performance.

Performance evaluation is based on metrics concerned with

1.
cohesion,

2.
line count,

3.
cyclomatic complexity of the code.

2.
Outline

In the following sections, I will discuss the

The different aspects that were dealt with in this research

Method Synchronization

Debugging

Code Profiling

Message Prioritization

Summary of results

Conclusions

Prospects for future work

3.1.
Method Synchronization

Consider the following cases:

Writing to a file.

Enqueue, Dequeue operations on a queue.

These are two classical cases that require
synchronization is orthogonal to purpose of
these operations, but vital as well.

Synchronization, hence, can be classified as
an Aspect.

3.1. Method Synchronization

Background

Synchronization is often achieved by
object
synchronization
, i.e., synchronizing the object:

The File stream in a file writing operation,

The Queue in an Enqueue / Dequeue operation.

Here, I discuss
method synchronization

using AOP.

A thread that enters must complete before another enters.

Methods synchronized with the same attribute do not
execute simultaneously.

3.1. Method Synchronization

Purpose

1.
Method synchronization offers a simple solution to synchronize
methods, even if the methods belong to different types.

2.
Quite often in object synchronization, the synchronized object is
locked throughout the method execution. Method
synchronization offers a more purpose
-
specific substitute for
these applications, by removing the synchronizing code from
the body of the methods.

3.
Method synchronization can be used for synchronizing even
those sets of methods that DON’T work on a common object.

3.1. Method Synchronization

Technique

[Sync("Q")]

public

void

EnQ(
string

msg)

{

this
.Q.Enqueue(msg);

}

[Sync("Q")]

public

string

DeQ()

{

if
(
this
.Q.Count == 0)

throw

new

Exception();

else

return

(
string
)
this
.Q.Dequeue();

}

AOP code

Synchronization
aspect declared
using attribute

3.
What we don’t say here

Technically, a lot is going on to make all this
happen.

We’ve explained each step in some detail in
Chapter 2 of the Thesis

Discusses basis for interception.

Chapter 3 discusses how interception is
applied to Method Synchronization.

3.1. Method Synchronization

Analysis

Client code statistics:

AOP library statistics:

Non
-
AOP

AOP

Lines

of

function

code

46

18

Cyclomatic

complexity

7

4

Cohesion

7

Aspect

code

Interception code

Lines

of

function

code

53

67

Cyclomatic

complexity

19

7

3.1. Method Synchronization

Contribution

Invented a new way of achieving Method
-
Synchronization in a .NET environment

Developed a .NET library that isolates the
synchronization aspect into a module, and
enables client code developers to plug this
aspect into their application

Analyzed the incremental benefit and cost
to use AOP for Method Synchronization.

3.2.
Debugging

A debugger application helps a client
-
code
developer functionally interact with the code
under execution.

A
debugger

should have at least some basic
features, like capability to

programmatically set break points,

to restart the process being debugged,

to print out a stack trace,

to manipulate argument values

3.2.
Debugging

Introduction

Here, we discuss a new way to develop ‘debugger’
facilities that integrate into an application.

We think that integrated debugging may be very useful for
vertical niche applications like Radar processing.

‘Debugging’ is an aspect, and employing AOP is an
effective way to develop applications with integrated
‘debugging’ capabilities.

This aspect can be successfully isolated into a
library, and used with client code to develop a
debugger
-
integrated aspect
-
oriented code.

What This Debugger Does

The custom debugger application that we have
developed using AOP has facilities to:

Programmatically set break points

Manipulate input parameter values from sink stack

Print out the stack trace in case of an exception

Manipulate the return value

Ignore a return
-
exception, and substitute it with a
dummy return value

Restart the application, all over again, at any point
during execution

3.2. Debugging

Architecture

3.2. Debugging

Technique

Enabling / Disabling Debugging

[DebuggerContext(
true
)]

public

class

Closed : System.ContextBoundObject

{

// Closed figure class.

}

[DebuggerContext(
false
)]

public

class

Closed : System.ContextBoundObject

{

// Closed figure class.

}

Enable debugging

Disable debugging

3.2. Debugging

Technique

Programmatically setting up break points

[DebuggerContext(
true
)]

public

class

Closed : System.ContextBoundObject

{

[Debug(
true
)]

public

double

ClosedCalcArea(
double

Area)

{

// method implementation

}

}

Break point

3.2. Debugging

Technique

Traces info regarding

Argument

Method

Instance

Parameters

3.2. Debugging

Technique

Pre
-
processing

Editing the
argument value

Application console

Debugger window

3.2. Debugging

Technique

Post
-
processing

An exception may be
negated!

Printing out the stack trace

Process may be restarted

3.2. Debugging

Technique

Tracing code segment that raised exception

3.2. Debugging

Contribution

Our primary contribution has been in identifying that
debugging is an aspect
-

Debugging features can be
integrated into application code using AOP.

We have developed, for the purpose of illustration, a
custom interception library which performs debugging
services by intercepting method calls.

Integrated Debuggers could be quite valuable for
specialized applications.

3.3.
Code profiling

Code profiling is the process of analyzing and
quantifying the quality of a piece of code.

Here, we propose that
code profiling

applications can
be developed effectively using AOP.

Code profiling areas that we have explored are

Code Coverage
:

We discuss an Aspect
-
Oriented approach to develop code
coverage applications.

Time Profiling
:

We illustrate an execution
-
time profiler application developed
using AOP

3.3.1. Code
coverage

code coverage analysis:
the process of discovering
methods in a program that are not examined using a
set of test cases.

Test drivers are executive codes that explore the
functioning of a program. The two primary goals of a
test driver are to

test all the
methods

in a program, and

to determine if they gracefully handle probing test cases
supplying both good and bad inputs.

Code coverage analysis is a means to help the test
driver designer achieve the first purpose
-

finding out
if
all

the methods in a program have been tested.

3.3.1. Code coverage

Technique

[ Profile (
true
) ]

public class

MyClass : System.ContextBoundObject

{

// class implementation

}

True
:
Enable

code coverage profiling

False
:
Disable

profiling

3.3.2.
Time Profiling

Time profiling:
the process of finding out the time of
execution of a method call with a specified set of
parameters.

A time profiler collects data about how much time is
consumed by the different methods in the program,
with any specified argument list. This information
enables the programmer to find out if execution times
of various functions are acceptable.

Here, we explore AOP
-
based time profiling based on
run
-
time interception of method calls

3.3.2. Time profiling

Technique

[ TimeProfile (
true
) ]

public class

MyClass : System.ContextBoundObject

{

// class implementation

}

True
:
Enable

time profiling

False
:
Disable

time profiling

3.3.2. Time profiling

Critical issues

1.
Issue
: Accuracy of time measurement:

Solution

-

The AOP library uses a high
-
resolution timer (least

count = 1 micro second) to determine the time of

execution of any intercepted method call.

2.

Issue
-
context message passing:

Solution

-

To reduce this inaccuracy, we employ ‘null

interval’ techniques.

3.3.Code profiling

Contributions

Identified aspect
-
oriented ways to develop
code
coverage

applications.

Explored AOP
-
based
time profiling
-

A couple of issues regarding inaccuracy of
measurement were identified, and solutions have
been proposed.

The code profiler has been applied to a medium
sized prototype application with interesting
results.

3.4.
Prioritization

Consider a typical distributed computing system,
where many clients talk to one server.

Due to its limited processing potential, a single
-
server
environment requires effective and well
-
defined priority
criteria

for its clients, and for the messages it needs
to process.

Prioritization may be a crucial issue in a single
-
server
environment, or generally in any system where the
server’s workload is quite heavy compared to its
processing power.

3.4. Prioritization

Introduction

Priority assignment of messages is
not

the actual

Similarly, prioritizing its clients is
not

the actual
business of the server. Ideally, however, the server
would have a provision for processing high priority
clients first.

It would be useful if all distributed systems had a
provision for prioritizing messages and clients, though
each new developer would prefer not to have to
produce code developed solely for this purpose.

For these reasons, we explore ‘
prioritization
’ as an
aspect

3.4.1.
Client

Prioritization

A server might need to handle requests from various
clients; of these some clients might require higher
priority than the others. For instance, in the case of a
simple LAN, client prioritization may mean that the
requests from an administrator be given higher
priority than requests from staff personnel.

Client prioritization

is the feature that enables the
server to process messages from different clients
based on the priority levels of those clients
.

3.4.1. Client Prioritization

Technique

here

Specifying clients’ priorities in a
file at the server side

3.4.2.
Message

Prioritization

In a distributed computing system, clients send
different types of messages to the server. Of these,
some require higher priority than the others. For
instance, an ‘Error’ message might be of higher
priority than an ‘File
-
transfer’ message.

Message prioritization

is the feature that enables a
client to set a priority level for messages being sent
to the server
.

3.4.2. Message Prioritization

Technique

priority assignment”
logic here.

3.4. Prioritization

Contribution

Our primary contribution in this chapter has been in identifying
that prioritization can be classified as an aspect of a distributed
computing system, and can be successfully isolated into a
separate module using AOP.

We have explored AOP
-
based

client prioritization and

message prioritization

as two specialized cases of priority assignment.

The methods discussed here have been demonstrated on small
prototype examples.

4.
Analysis

Let us quickly review the aspects that were
dealt with in this thesis presentation:

a
Range
-
Checker

application, involving validation

“Method Synchronization”

“Debugging”

“Code
-
Profiling”

Code coverage

Time profiling

“Prioritization”.

Client prioritization

Message prioritization

4. Analysis

Aspect

Whether or not analyzed

Range
-
Checking (Validation)

Yes

Method Synchronization

Yes

Debugging

NOT

performed

Reason
: Difficult to develop non
-
AOP
“Debugger” code that can be integrated
with application code

Code Profiling

NOT

performed

Reason
: Difficult to develop non
-
AOP
“Profiling” code that can be integrated with
application code

Prioritization

Yes

4. Analysis

Integrated results

Without

AOP

With

AOP

Lines

in

the

body

of

the

function

(for

the

maintainable

code)

68

19

72 %

reduction

Cyclomatic

complexity

(for

the

maintainable

code)

29

13

55 %

reduction

Cyclomatic complexity of aspect
-
specific
library code

55

Cohesion

of

client

code

44 %

reduction

Analysis performed on
nine methods

over
three sets

of applications

5.
Conclusions

Based on 9 Methods in 3 Applications

1. + AOP reduces client code complexity:

Cyclomatic complexity of 9 client methods over 3 applications:

Non
-
AOP: 29

AOP
-
based: 13 (
55
% reduction )

The AOP
-
server code, though, suffers from a high cyclomatic
complexity. This is acceptable since the AOP
-
server library is a
one
-
time development

does not need change from application
to application.

5. Conclusion

2. + AOP improves cohesion:

An advantage of AOP is its potential for improving the
cohesion of methods.

Cohesion:

Non
-

AOP

44

% reduction )

5. Conclusion

3. + AOP captures the purpose of code better:

public

double

Geometry_FindSectorArea(
double

double

angle)

{

if

throw

new

if

( (angle < 0.0) || (angle > 6.2832) )

throw

new

ArgumentOutOfRangeException("angle", "angle is out of range");

double

if

( result < 0 )

throw new

ArgumentOutOfRangeException(“return value out of range");

return result;

}

[
return
: RangeCheck(
true
, Lower = 0.0)]

public

double

Geometry_FindSectorArea

([RangeCheck(
true
, Lower = 0.0)]
double

[RangeCheck(
true
, Lower = 0.0, Upper = 6.28)]
double

angle)

{

return

}

Non
-
AOP

AOP
-
based

5. Conclusion

4. + AOP promotes reusability

An interception library isolates an aspect

is generic

NOT application specific.

Pluggable

use wherever needed

and hence promotes software reuse.

5. Conclusion

5.
-

Interception
-
based AOP comes with a performance
penalty:

To enable AOP
-
based interception, we force inter
-
context message passing which would insert
overhead and so hamper performance. Again,
messages are intercepted at run
-
time; this would
negatively affect performance

The overhead of interception though is much
smaller than the execution time of a typical
method.

0
20
40
60
80
100
120
1
2
3
Series1
6.
Future work

This thesis creates several opportunities for future
research on AOP:

-
balancing

Clustering technology

-

In this research, we have used run
-
time interception
-
based implementation of AOP. As part of a future
project, we plan to explore AOP using customized
proxies.

7.
Summary

In this research, we analyzed efficacy of AOP under the .NET
environment.

We identified several applications where aspect
-
oriented
approach can be effectively applied

Method
-
Synchronization,

Debugging,

Code
-
Profiling,

Prioritization, and

Validation.

For three aspect
-
oriented applications, we evaluated the impact
of AOP on code complexity and performance.

Finally, we summarized our contributions and conclusions, and
made suggestions for future work using AOP.

8.
References

In the Bibliography of the Thesis document
we refer to:

Twenty two articles from conferences and
refereed journals.

The most relevant of these are two articles by
G. Kiczales, et. al., and one by Schul and Polz.

Seven books on the .Net technologies

Two web sites

Thank You!