Top Banner
Erlend Rønningen and Tore Steinmoen Increasing readability with Aspect-Oriented Programming Restructuring an object-oriented system with aspects Project assignment in TDT4735 Software Engineering, Specialization Supervisor: Tor Stålhane Thesis advisor: Kristoffer Kvam Department of Computer and Information Science (IDI) Norwegian University of Science and Technology (NTNU)
118

Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

May 15, 2020

Download

Documents

dariahiddleston
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

Erlend Rønningen and Tore Steinmoen

Increasing readability with

Aspect-Oriented Programming

Restructuring an object-oriented system with aspects

Project assignment in

TDT4735 Software Engineering, Specialization

Supervisor: Tor Stålhane

Thesis advisor: Kristoffer Kvam

Department of Computer and Information Science (IDI)

Norwegian University of Science and Technology (NTNU)

Page 2: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- ii -

Page 3: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- iii -

AAbbssttrraacctt

Aspect-oriented programming (AOP) is a paradigm aiming to solve some of the shortcomings

of object-oriented programming (OOP). With ordinary OOP it’s often impossible to achieve

good system modularity due to crosscutting concerns being scattered throughout the system.

AOP resolves this problem by its ability to crosscut the regular code and as a result move the

support functionality to a single location. With this report we want to study whether AOP is

able to improve the readability of a selected system’s code. To explore this we will restructure

the object-oriented system with AOP. To calculate the effects on the restructured system we

will use a number of metrics and from this evaluate whether the system has been improved or

not.

Page 4: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- iv -

Page 5: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- v -

SSuummmmaarryy

We have studied Aspect-Oriented Programming and the effects of introducing aspects in an

object-oriented system with the following problem definition “Can restructuring an object-

oriented system with aspects increase its readability?”

Concretisized, we have studied the effects of restructuring the system DIAS 2, which

originally is a part of a master thesis at NTNU. The system is implemented in Java, and we

used AspectJ to restructure it. We introduced nine new aspects and measured the effects

within three areas: code size, complexity and structure. Readability is assumed to depend on

these areas.

We defined code lines within methods to be the measure of code size, and we got a 16.12

percent reduction after restructuring the code. This number does not include generated code,

which is approx. 40 percent of the total code.

Multiple different metrics were used to measure the complexity. We have a reduction in fan-

out, efferent coupling, Henry’s and Kafura’s Complexity and McCabe’s cyclomatic

complexity, while fan- in and afferent coupling is not reduced.

We used two different metrics when measuring code structure. They were lack of cohesion

and the number of hidden concerns. We got a small reduction in lack of cohesion, and we

have found nine hidden concerns in the system.

The conclusion of our study is that we have increased readability of the chosen system

through reduced code size, reduced complexity and better structure.

Page 6: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- vi -

Page 7: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- vii -

PPrreeffaaccee

This report is the result of the project work in the course “TDT4735 Software Engineering,

Specialization” at the Department of Computer and Information Science (IDI), at the

Norwegian University of Science and Technology (NTNU). This work is a part of our five

years Master’s Degree and is a preparation for our post-graduate thesis.

We have studied the impacts of restructuring an object-oriented system with aspects. The idea

for this project was conceived during summer work at Telenor Mobile AS. During our time at

Telenor Mobile we also came to an agreement that they would be partners in our project. We

would like to thank Paul Skrede for accepting our suggestions and making the agreement.

We would also like to thank our advisor at Telenor, Kristoffer Kvam, for valuable

suggestions, guidance and reading through our text.

Last, but definitely not least, we would like to thank our advisor at NTNU, Professor Tor

Stålhane. You have given us most valuable guidance, motivation and innumerable corrections

of our bad language.

Trondheim, 27 November 2003

------------------------------------- -------------------------------------

Erlend Rønningen Tore Steinmoen

Page 8: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- viii -

TTaabbllee ooff CCoonntteennttss

Abstract .......................................................................................iii

Summary .......................................................................................v

Preface ....................................................................................... vii

Table of Contents.......................................................................... viii

Figures and tables ............................................................................x

Chapter 1. Introduction.....................................................................1

1.1. Background Aspect-oriented programming ........................................................... 1

1.2. Problem definition.................................................................................................. 2

1.3. Project work goals .................................................................................................. 3

1.4. Report outline ......................................................................................................... 3

Chapter 2. Prestudy..........................................................................5

2.1. Programming paradigms ........................................................................................ 5

2.2. Software engineering metrics ................................................................................. 6

2.3. What is missing in Object-oriented programming? ............................................... 9

2.4. What is Aspect-oriented programming? .............................................................. 11

2.5. Why use Aspect-oriented programming?............................................................. 14

2.6. When not to use AOP?......................................................................................... 17

2.7. Programming languages and tools ....................................................................... 18

2.8. Other techniques................................................................................................... 20

2.9. Similar research.................................................................................................... 21

2.10. Refactoring ........................................................................................................... 23

2.11. Systems to be explored......................................................................................... 23

Chapter 3. Research agenda.............................................................. 27

3.1. Research method .................................................................................................. 27

3.2. Overall work plan................................................................................................. 28

Chapter 4. Metrics for evaluating readability ......................................... 31

Page 9: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- ix -

Chapter 5. Decide on technology........................................................ 35

5.1. Programming languages ....................................................................................... 35

5.2. Development tools ................................................................................................ 37

Chapter 6. Identifying crosscutting concerns ......................................... 39

6.1. Analysis of system documentation....................................................................... 40

6.2. Type-based analysis ............................................................................................. 41

6.3. Copy n’ paste analysis .......................................................................................... 43

6.4. Text-based analysis .............................................................................................. 44

6.5. General experiences from the aspect mining ....................................................... 45

Chapter 7. Implementation............................................................... 47

7.1. The Iraqi war ........................................................................................................ 47

7.2. DIAS 2.................................................................................................................. 50

Chapter 8. Results .......................................................................... 55

8.1. Code lines within methods ................................................................................... 55

8.2. Complexity........................................................................................................... 56

8.3. Structure ............................................................................................................... 60

8.4. Readability ........................................................................................................... 62

Chapter 9. Discussion...................................................................... 63

9.1. Code size .............................................................................................................. 64

9.2. Complexity........................................................................................................... 65

9.3. Structure ............................................................................................................... 67

9.4. Readability ........................................................................................................... 67

Chapter 10. Conclusion.................................................................... 69

Chapter 11. Further work................................................................. 71

Appendix A. References................................................................... 75

Appendix B. Glossary ...................................................................... 81

Appendix C. Code from The Iraqi War.................................................. 87

Appendix D. Code from DIAS 2........................................................... 95

Page 10: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- x -

FFiigguurreess aanndd ttaabblleess

FFiigguurreess

Figure 1 Crosscutting concerns in UML class diagram: all the methods encapsulated have

to check if user has the right to perform this action. ............................................. 12

Figure 2 Joinpoints in UML sequence diagram. The calling and returning of methods can

be used as joinpoints. ............................................................................................ 13

Figure 3 Enforcing that no messages are sent between layers that aren’t adjacent. ............ 15

Figure 4 The overall architecture of DIAS2 ........................................................................ 25

Figure 5 Work plan for our study of DIAS 2....................................................................... 29

Figure 6 The step of finding metrics highlighted in the work plan. .................................... 31

Figure 7 The transition from goal to question using GQM. ................................................ 32

Figure 8 The metrics used to answer the GQM questions................................................... 32

Figure 9 The task of deciding on technology highlighted in the work plan. ....................... 35

Figure 10 The tasks involved in identifying crosscutting concerns are highlighted in the

work plan. .............................................................................................................. 39

Figure 11 Equal sub trees in activity diagram of the Communicate method in two different

classes in DIAS2. .................................................................................................. 40

Figure 12 The Aspect Mining Tool v.0.6a [49] used on the original DIAS 2 code. ............. 41

Figure 13 Finding copy n' paste code with the CPD tool. ..................................................... 43

Figure 14 Code from DIAS 2 shown in the Eclipse v.2.1 IDE [47]...................................... 44

Figure 15 The task of implementing aspects is highlighted in the work plan. ...................... 47

Figure 16 The original code in The Iraqi war ........................................................................ 48

Figure 17 A pointcut in AspectJ defines a set of joinpoints. ................................................. 48

Page 11: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- xi -

Figure 18 An advice defines what actions take place at defined pointcuts. .......................... 49

Figure 19 Support for readability in the Eclipse IDE provided by the AspectJ plug- in........ 49

Figure 20 Introduction of properties to an interface and introducing that interface to classes

............................................................................................................................... 53

Figure 21 Code lines within methods. ................................................................................... 55

Figure 22 Code lines within methods by package. ................................................................ 56

Figure 23 Distribution of fan- in of edited source. ................................................................. 59

Figure 24 Mean and standard deviation values for Weighted Methods per Class (WMC)... 61

Figure 25 Radar plot of readability attributes ........................................................................ 62

Figure 26 Use of the ExcpetionPrinter aspect on the package level. ..................................... 65

Figure 27 Coupling between objects in Java vs. Aspect program......................................... 66

TTaabblleess

Table 1 Comparing our study with previous studies. ......................................................... 23

Table 2 The main components of the DIAS 2 system. ....................................................... 26

Table 3 Comparison of AspectJ and AspectWerkz............................................................ 36

Table 4 Implementation of crosscutting concerns in DIAS 2 ............................................ 52

Table 5 Measures of afferent coupling............................................................................... 57

Table 6 Measures of efferent coupling. .............................................................................. 58

Table 7 Measures of fan- in................................................................................................. 58

Table 8 Measures of fan out. .............................................................................................. 59

Table 9 Measures of Henry's and Kafura's complexity based on LOC.............................. 60

Table 10 Measures of Henderson-Sellers’ lack of cohesion of methods. ............................ 61

Page 12: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- xii -

Page 13: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

CChhaapptteerr 11.. IInnttrroodduuccttiioonn

We have chosen to study aspect-oriented programming (AOP), trying to understand the

fundamental concepts, the advantages and disadvantages, and practical use of AOP. This was

first introduced to us at Telenor Mobile. They were in a phase of exploring how AOP could

contribute to their system development process. We came to an agreement with Telenor

Mobile that they would be our partners for this project. We also found that no one in the

academic staff at NTNU had any experience with AOP. Thus it seemed beneficial for the

university to explore this subject as well.

11..11.. BBaacckkggrroouunndd AAssppeecctt--oorriieenntteedd pprrooggrraammmmiinngg

Aspect-oriented programming is a programming paradigm invented at Xerox Parc in the

1990s. MIT Technology review wrote in 2001 that AOP is among "ten emerging areas of

technology that will soon have a profound impact on the economy and on how we live and

work" [8].

Today AOP is rapidly developing as a concept within software development. There have been

a great number of articles published during the latest three years. According to Kiczales et al.,

AOP research today can be seen as similar to OOP research 20 years ago, rapidly growing as

an area of research [2].

The motivation behind AOP [2] [17] is that existing programming languages cannot

represent independent concerns like synchronization, resource sharing, distribution or

debugging in a single module. Rather than being localized within a program unit, like a class,

these concerns are orthogonal to the system’s basic program units and module structure.

Page 14: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 2 -

11..22.. PPrroobblleemm ddeeffiinniittiioonn

When we first chose AOP as the subject for our project we defined our interests to be:

o Learn more about AOP, the possibilities and the available tools

o Make evaluations of languages and tools

o Find out more about how to use the concept of AOP within the process of software

development

o Find out more about what is a good design when using AOP for a system

These points were only starting points to elaborate on, concretize on and choose between.

They are also possibilities for further work after this project.

After learning more about AOP through reading articles, attending an AOP-workshop,

discussing with our supervisor and doing some programming, we found a subject that seemed

both interesting and accomplishable.

A key claim about AOP is that it, through better modularization, will increase the readability

of programs [19] [20]. We want to explore this, since we find it to be an important factor

when choosing to use AOP or not.

We have chosen to be even more specific, when choosing what kind of development we will

study. Instead of making a new system from scratch we have chosen to restructure an existing

system.

We arrive at this problem definition:

CCaann rreessttrruuccttuurriinngg aann oobbjjeecctt--oorriieenntteedd ssyysstteemm

wwiitthh aassppeeccttss iinnccrreeaassee iittss rreeaaddaabbiilliittyy??

Page 15: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 3 -

11..33.. PPrroojjeecctt wwoorrkk ggooaallss

With the problem definition as a starting point, we have defined the following work goals for

this project:

o Present a theoretical fundament for AOP and the concerns relevant for studying this

concept.

o Give reasons to introduce AOP when already using an object-oriented programming

language.

o Choose an aspect-oriented language for our programming implementations.

o Implement one small system and a medium sized system in the language we have

chosen.

o Analyze the chosen medium sized system by applying metrics before and after we

have restructured it with AOP. This will help us see if the system has benefited from

the restructuring effort.

o Make conclusions about readability based on our findings.

11..44.. RReeppoorrtt oouuttlliinnee

• Introduction

• Prestudy

• Research agenda

• Problem elaboration

• Own contribution

• Results

• Evaluation and discussion

• Conclusion and further work

• Appendices

Page 16: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 4 -

Page 17: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 5 -

CChhaapptteerr 22.. PPrreessttuuddyy

In this chapter we introduce principles and definitions of object-oriented metrics, and we

argue the need to improve OOP designs and implementations. We give a historical and

theoretical background for AOP, discuss AOP’s advantages and disadvantages, and present

state-of-the-art practice in the research area of AOP. Further, we introduce the term

refactoring and present the two systems used in our study.

22..11.. PPrrooggrraammmmiinngg ppaarraaddiiggmmss

The widespread use of programming languages began with the arrival of FORTRAN in 1957

which according to Sethi [1] took readable formulas and translated them into IBM 704

machine language.

The main reasons for making higher level languages are improved readability, machine

independence, availability of program libraries and consistency checks [1]. A key concept

when talking about programming languages is modularity. A module is considered to be a

responsibility assignment, not just a subprogram (Parnas, [3]).

FORTRAN is like C and Pascal defined to be imperative programming languages. These

languages have actions as basic units and offers little help for modularizing the code [3].

Fundamental to object-oriented programming is modularity through encapsulation. Other

features are information hiding, user-defined classes, message passing, inheritance and

polymorphism, according to Nierstrasz [4]. Object-oriented programming is founded on ideas

from Simula, designed by Kristen Nygaard and Ole Johan Dahl in the 1960s. Smalltalk, C++

and Java are popular object-oriented languages.

Page 18: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 6 -

Other programming paradigms exist. They are typically founded on a problem domain; like

functional programming is well suited when developing applications for artificial intelligence

and logical programming is founded on logical reasoning.

22..22.. SSooffttwwaarree eennggiinneeeerriinngg mmeettrriiccss

Metrics are used to study the effects of changes to a code base. We present such metrics for

use with object-oriented software.

Berard [63] characterizes the following uses for object-oriented (OO) software engineering

metrics:

o Measuring OO software engineering products, e.g. designs, source code, and test

cases.

o Measuring OO software engineering processes, e.g. the activities of analysis,

designing, and coding.

o Measuring OO software engineering people, e.g. the efficiency of an individual tester,

or the productivity of an individual designer.

Software engineering metrics allow us to [63]:

o quantitatively define success and failure, and/or the degree of success or failure, for a

product, a process, or a person.

o identify and quantify improvement, lack of improvement, or degradation in products,

processes, and people.

o make meaningful and useful managerial and technical decisions.

o identify trends.

o make quantified and meaningful estimates.

Further on, Berard [63] argues that using a single metric is seldom useful. Up to five well-

chosen metrics are needed to get a good indication of a process, product or persons attributes.

Page 19: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 7 -

The most useful set of metrics may not be known ahead of time. This implies that to study

some aspect of software engineering we may need to use a larger number of metrics. Later,

analysis should point out the most useful metrics.

It is important to note that metrics are almost always interrelated. Influencing one metric may

often have an impact on other metrics for the same process, product or person.

MMeettrriiccss uusseedd ffoorr mmeeaassuurriinngg rreeaaddaabbiilliittyy

The following is a definition of metrics that have been used in order to estimate whether

readability has been improved:

a. Lines of code

Lines of code are measured as non-comment and non-blank lines inside method bodies.

b. Coupling

According to McGraw-Hill [32] coupling can be defined as the following:

“Coupling refers to the strength of the linkage between two modules, based on the amount

and kinds of information they exchange. Minimal coupling is a design goal. The worst type of

coupling is among modules that share global data (data that are defined outside the scope of

individual modules). The best is coupling where modules manipulate the same data type.”

Afferent coupling is the number of classes outside a specific module that depend on the

module. Efferent coupling is the number of dependencies a specific module has to classes

outside the module. For more information about afferent and efferent coupling, see the

documentation of the metrics tool JDepend [7].

c. Fan-in / fan-out

In Sommerville [50] we find the following definition of fan- in and fan-out. Fan- in is a

measure of the number of functions that call some other function (say X). A high value for

fan- in means that X is tightly coupled to the rest of the design. Changes to X will have

Page 20: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 8 -

extensive knock-on effects. Fan-out is the number of functions which are called by function

X. A high value for fan-out suggests that the overall complexity of X may be high due to the

control logic needed to coordinate the called components. Henry and Kafura [53] defined a

complexity measure based on fan- in/fan-out:

Complexity = Length x (Fan- in x Fan-out)2

Length is any measure of length such as lines of code, or alternatively McCabe’s cyclomatic

complexity may be used as a substitute.

d. McCabe’s cyclomatic complexity

McCabe’s cyclomatic complexity measures the amount of decision logic in a single software

module [52]. This system measures the number of independent paths in a program, thereby

placing a numerical value on the complexity. In practice it is a count of the number of test

conditions in a program. The cyclomatic complexity (CC) of a graph (G) may be computed

according to the following formula [51]:

CC(G) = Number (edges) - Number (nodes) + 1

A drawback of the cyclomatic complexity metric is that it measures a program’s control

complexity and not the data complexity. Further on, it weighs non-nested and nested loops

equally. Shepperd [65] criticized McCabe’s cyclomatic complexity, stating “it is based upon

poor theoretical foundations,” and as such should not be used as a predictor for reliability and

development effort. The cyclomatic complexity is also strongly correlated to lines of code.

e. Cohesion

According to McGraw-Hill [32] cohesion can be defined as the following:

“Cohesion refers to the degree to which parts of a program unit, for example functions in a

module, are related. A highly cohesive module performs a single task and can usually be

described by a specific verb and object like "print a file" or "sort a list." The best type of

cohesion is among elements that jointly implement an abstract data type. More cohesive

modules tend to be more modular and to be easier to understand and document.” We have

doubts about the usefulness of this metric in Java since it penalizes the proper use of getter

Page 21: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 9 -

and setter methods to accessing an attribute [35].

f. Weighted Method Complexity

Weighted Method Complexity is the number of methods included in a class weighted by the

complexity of each method. The larger the value for this metric, the more complex the object

class is [50]. A common way of measur ing complexity of the methods is to use the

complexity number. This number is calculated with the following formula: V(G) = d + 1,

where d is the amount of decision nodes.

f. Depth of Inheritance Tree and Number of Children

Zakaria and Hosny [43] suggest Depth of Inheritance Tree (DIT) and Number of Children

(NOC) as measures for improved understandability when using AOP. You need a special kind

of code behaviour to observe changes in these two metrics. “Subclasses that might be defined

only for the purpose of applying their own implementation of aspectual behaviour will not exist in

systems designed using the AO Paradigm, because aspects will be responsible for that.” [43]

g. Response For a Class

Response For a Class (RFC) is also a recommended metric, that measures the number of

methods that can be invoked in a class in response to a message [43]. This metric can be used

to evaluate understandability, maintainability and testability.

22..33.. WWhhaatt iiss mmiissssiinngg iinn OObbjjeecctt--oorriieenntteedd pprrooggrraammmmiinngg??

In this report we focus on using aspects together with OOP. It is therefore interesting to

discuss the main disadvantages of OOP.

According to Brooks (1987) [23], OOP removes a difficulty from the software process by

allowing the designer to express the essence of the design without having to express large

amounts of syntactic material that adds no information. But Brooks [23] also states that this

Page 22: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 10 -

paradigm can not do more than remove accidental difficulties from the design. The

complexity of the design itself is still present.

According to Eder et al. [5], a severe problem encountered in object-oriented system

development is the quickly increasing complexity of such systems, which is due to the many

objects and inter-relations between these objects. This leads to strong dependencies between

objects, know as high coupling, and weak bindings inside objects, known as low cohesion.

This is the opposite of what you get with good modularity, where you have objects with

strong inner relations and few couplings to other objects.

Hannemann and Kiczales [6] introduced the concept of hidden concerns. The OOP approach

of modularizing software systems according to a single concern might not provide enough

structure for developing complex systems. Concerns not represented in the current system

decomposition have to be forced onto the primary decomposition. Code related to these types

of hidden concerns can show up as two symptoms of poor modularity:

o The concern’s code is scattered throughout the system.

o The concern’s code is tangled with other code.

As a consequence hidden concerns can lead to:

o Inconsistency when modifying the code. Some occurrences of the code can be

forgotten, so that changes are performed in some places but not in all.

o Less readable code. It can become difficult to understand what the primary

functionality of a method is, because you have to read through code blocks of support

functionality (for instance code for logging, tracing, caching, security, etc).

o Poorer maintainability. It is harder to keep track of where changes need to be made.

o Inflexible code as the system is changed over time. Restructuring is often too costly,

which instead leads to coupling across the original architecture. In the end, the code is

so tangled that maintenance becomes difficult.

Page 23: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 11 -

o Violations of code standards and development procedures. This is a factor that can

lead to the problems mentioned above, since it in effect leads to inconsistency in the

way of writing and structuring code among the developers.

22..44.. WWhhaatt iiss AAssppeecctt--oorriieenntteedd pprrooggrraammmmiinngg??

When talking about AOP it is important to note is that it is not a standalone programming

paradigm like object-oriented programming and imperative programming. AOP is always

used together with other programming paradigms.

FFoorrmmaall eexxppllaannaattiioonn

Filman and Friedman [10] have worked with defining what aspect-oriented languages are, and

they came to the following explanation:

To understand this explanation we must define the following:

o Quantified statements are statements that affect the underlying code in many places.

o Oblivious programmer is one who does not have to spend any additional effort to

make the AOP mechanism work.

We have two types of quantification, meaning the places where the new actions have effect:

1. Static quantifications can be divided into:

a. black box quantification, that is made only over the public interfaces of the

underlying code.

b. clear box quantification, that is made over the parsed structure of the

underlying code.

“AOP can be understood as the desire to make quantified statements about the behavior

of programs and to have these quantifications holds over programs written by oblivious

programmers.”

Page 24: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 12 -

2. Dynamic quantifications are made over run-time events like e.g. calling of

subprogram and raising of exceptions.

The terms in the explanation above can be translated into new domain specific terms. In the

AOP-domain we talk about concerns, joinpoints and aspects.

CCoonncceerrnnss

We can define concerns as properties or areas of interest in a system. Separation of concerns

is a main principle in software engineering [3]. According to Kiczales et al [2], a concern

must be implemented as:

o a component, if it can be cleanly encapsulated in a generalized procedure

o an aspect, if it can not be cleanly encapsulated in a generalized procedure

AOP provides a way of encapsulating crosscutting concerns. Concerns crosscut if the

methods related to those concerns intersect [20], both inside a class or over several classes.

This can be seen in figure 1 where all those methods marked have to check the user rights.

Figure 1 Crosscutting concerns in UML class diagram: all the methods encapsulated have to check if user has the right to perform this action.

File

open()

read()

write()

close()

Catalog

open()

read()

write()

close()

Check user rights *

User

Page 25: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 13 -

Such concerns can be based both on functional and non-functional requirements. Examples

are logging, security, caching or buffering.

JJooiinnppooiinnttss

Joinpoints are the locations which are affected by one or more of the crosscutting concerns. In

Figure 2 we can see examples of possible joinpoints as the calling and returning of a method.

Joinpoints are the locations where we can hook on new actions before or after the original

code execution. As mentioned in the explanation, we can hook actions on to the static or

dynamic structure of the program.

Figure 2 Joinpoints in UML sequence diagram. The calling and returning of methods can be used as joinpoints.

AAssppeeccttss

Fundamental to AOP is the definition of aspects. Kiczales et al [2] wrote in 1997 that aspects

are design decisions that are difficult to address in actual code because they crosscut the

system.

With AOP we can separate aspects from the underlying structure of the code; as in the

example shown in figure 1. In the example we can move the updating of the display to a

separate subprogram. This subprogram we call an aspect.

this:

User

root:

Catalog

Open()

Joinpoints

Page 26: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 14 -

22..55.. WWhhyy uussee AAssppeecctt--oorriieenntteedd pprrooggrraammmmiinngg??

Aspect-oriented programming claim to contribute to solve the problems mentioned for OOP.

In this part we present how AOP can help and support system development.

AOP gives the developer the opportunity to move distracting support functionality away from

the primary code. Voelter [13] described how functionality that cut across modules can be

gathered at a single location, in an aspect. He claims there is no risk for inconsistency since a

modification of the aspect code will be applied everywhere the aspect is used. AOP

counteracts scattering by gathering the code in one aspect, which enables system wide

changes to be made in one location. Maintainability is improved as changes only have to be

performed in one place, and it is easier to maintain an overview of the effects of changing a

particular part of the code.

The collection of code in aspects minimizes the risk of redundancy, and it is claimed that it

will improve the reuse of code. Aspects that handles testing and logging, as well as

performance measurements and exception handling, can in many instances be reused in later

projects with minor modifications. Since the support functionality can be delegated to an

aspect, the primary functionality becomes more readable and easier to understand (Bodkin

[22]).

Zhang [12] has shown that AOP reduces the need to make couplings across the architecture

when making changes to the system. Code becomes more flexible as coupling between

system-components are lowered because of the use of aspects.

AOP supports automated procedures for violation control of code standards and procedures,

as covered by Bodkin [22]. This lessens the risk of the system becoming “chaotic” over time.

Static control at compile time is supported, in which warnings and error messages can easily

be generated. AOP can’t use dynamic data, as for instance the arguments of a method.

Example: The developer receives an error message during compilation, if an

exception is written to screen instead of being logged.

Page 27: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 15 -

Aspects can be used as an enforcement to verify that the design and architecture of the system

is followed. “The construction of complex, evolving software systems requires a high- level

design model. However, this model tends not to be enforced on the system, leaving room for

the implementers to diverge from it, thus differentiating the designed system from the actual

implemented one.” (Shomrat and Yehudai [14])

Figure 3 Enforcing that no messages are sent between layers that aren’t

adjacent.

Example: Bodkin [22] demonstrated how AOP can be used in a layered architecture.

By creating aspectisized interfaces it is possible to control that method calls don’t

cross multiple layers as seen in Figure 3.

According to Mendhekar [15], AOP can be used for performance optimization. In their

example system they increased performance by being able to remove the following problems

in the original OOP-architecture:

o Redundancy in computation

o Excess memory turnover

o Inefficient data cache usage.

AOP can add timers outside methods and both measure performance and perform controlling

actions on the method, like caching of return values from methods [22]. Note that if there is a

lot of variation in return values caching is not a good move.

Layer 1

Layer 2

Layer 3

Page 28: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 16 -

AOP has shown to be well suited for testing purposes, e.g. through unit testing and

combinations of smaller tests. This can be helpful when using extreme programming as the

development method [18]. AOP can be used to decide what data should be given to a

method, by creating mock-up objects. The mock-up objects mimic the behavior of the objects

the method would normally interact with, while the developer has total control over what the

mock-up objects gives as input and return values to the tested method.

Example: AOP mock-up objects makes the tester able to test the method’s ability to

handle for instance database crashes, without actually having to crash a database.

Using print statements at various points in the code is probably the simplest and most

common way of debugging, because according to Aydemir [11], it feels faster and less

troublesome than using the debuggers in integrated development environments (IDE). The

print statements become spread around the program, resulting in scattered and tangled code.

Aspects, on the other hand, can be used for debugging without interfering with the code

structure.

Example: There are tools that let the developer insert custom made logging- and

debugging-aspects, without needing to know how to program aspects, as with the

Turkolog tool [11].

Voelter [13] described how error handling can be left to aspects, instead of cluttering up the

code. Exceptions can be overridden, for instance by translating them into other kinds of

exceptions.

Example: An internal exception is sent to an internal log and then sent to the user as a

more understandable exception. The faith of the exception can be decided based on

the state of other variables. It is also possible to use an exception to make a new

attempt a finite number of times.

Security is something AOP is well suited for, as demonstrated by Viega [16]. Aspects make

for an easy location to place for instance log in-tasks and encryption.

Page 29: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 17 -

Domain-specific aspects are an area of future development. AOP have mostly been used for

middleware concerns, and domain-specific aspects haven’t been much explored yet. Auditing,

metering, alerts and event generation, object history and versioning are all possible domains

for using aspects. [22]

Feature management, e.g. custom made system versions for specific partners or cus tomers,

can be developed by using aspects. With such solution there is only need for one common

code base, and aspects can be turned on and off to customize the system to the specific

customer needs [22].

Business logic is, according to Bodkin, a domain that is seen as a logical step from where

AOP are today. This is not an area that has been much explored, as companies are still unsure

of what AOP has to offer [22].

22..66.. WWhheenn nnoott ttoo uussee AAOOPP??

This is a summary of what previous research has concluded about AOP’s limitations.

AOP can not save your system if the code is a total mess. If you have a system built on

"spaghetti-code" there's no use trying to utilize AOP on it. The system needs a fairly good

base structure, or else the process of finding good candidates for aspects will be close to

impossible [18]. An example of bad code is when the same problem has been solved in many

different ways throughout the code. This makes it complicated to extract them to aspects. A

related complication is identifying what parts of the code shares the same functionality.

Finally, it is hard to predict which other parts of the code could be affected by making

changes in one or more places.

AOP is not useful for singletons [10]. If something is only done once in the code, then there is

no reason for making an aspect as it is already as compact as it can possibly get. In the same

manner as for singletons, code with good modularity should most probably be left alone as

well. Parts of code that fit well together through regular OOP, has no need for aspects.

Page 30: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 18 -

“AOP can be beneficial, but only if it is used in the entire system. Using AOP for only single

tasks, such as testing, or implementing a single feature, will lead to additional overhead. The

more AOP is used in a project, the more it will be worth investing the initial learning

overhead" [18]. Also, the earlier in the development process and the more it is used, the more

beneficial is AOP.

In an interview with TheServerSide.com, Kiczales [24] states: "AOP is a modularity

technology - to the extent you have good developers, who understand the domain, AOP will

help them develop better, cleaner, more reusable code more quickly and easily.” But he also

points out that AOP will not make all software simple.

22..77.. PPrrooggrraammmmiinngg llaanngguuaaggeess aanndd ttoooollss

In this part we classify AOP languages and present examples for different languages.

CCllaassssiiff iiccaattiioonn ooff aann AAssppeecctt--OOrriieenntteedd PPrrooggrraammmmiinngg llaanngguuaaggee

An AOP-language uses five elements to modularize concerns according to Kiczales [20]:

1) A join point model describing hooks to add enhancements

2) Means of identifying join points

3) Means of specifying behaviour at join points

4) Encapsulated units combining join points specifications and behaviour

5) Methods of attachment of units to a program

GGeenneerraall JJaavvaa--bbaasseedd ttoooollss

There are mainly two general Java-based AOP tools. By general, we mean that they offer the

possibility of making own aspects within any domain. One tool is a language and the other is

a framework. Both are widely used and are no longer prototypes:

Page 31: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 19 -

1. AspectJ [36]:

This is a language which offers clear-box quantification over the structure of a Java-

program [10]. According to Kiczales [24], AspectJ has become a de facto standard.

The language offers a Java-like notation and is the most used AOP-extension. AspectJ

won a price for “Most Innovative Java Product or Technology” earlier this year [45].

2. AspectWerkz [37]:

This is a framework which is perhaps the main opponent to AspectJ in terms of

number of users. The main difference between these two is that AspectWerkz offers

introduction of aspects at runtime, in addition to what AspectJ offers [24]. This means

that you can turn aspects on and off at runtime. You can choose between an XML-

based notation or a Java framework.

OOtthheerr ttoooollss

There is an ongoing discussion whether the programmer needs to make own aspects or not.

One branch of the AOP community have come to the conclusion that all you need is some

predefined aspects or a domain specific framework. See Bodkin [22], Kiczales [24] and Pinto

et al. [25] for information on this discussion. Some examples are:

o JBoss-AOP [38]

JBoss is an open-source application server, which uses an AOP-architecture where you at

runtime can add or remove certain aspects, like locking, encryption and logging.

o JAC [39]

This is a framework for aspect-oriented distributed programming.

o Nanning [40]

This is a Java-based framework based on dynamic proxies and aspects implemented as

ordinary Java-classes.

Page 32: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 20 -

OOtthheerr llaanngguuaaggeess

There are also a number of AOP languages which use other base languages than Java. Two

examples are AspectC for C and AspectC++ for C++.

22..88.. OOtthheerr tteecchhnniiqquueess

There are techniques which are explicitly or closely related to AOP. Bellow we present a list

of such techniques. The list is not complete.

EExxpplliicciittllyy ccoonnnneecctteedd wwoorrkk

These techniques may be seen as AOP techniques:

• Composition Filters

According to Bergmans and Aksit [26], this technique uses filters to express

crosscutting concerns by enhancements to objects. The filters are independent of the

implementation of an object.

• Adaptive Programming

According to Lieberherr et al. [27], an adaptive method encapsulates the behavior of

an operation into one place. It then uses a traversal strategy to ensure that the

operation is done where needed. A traversal strategy crosscuts the graphs it is intended

for, only mentioning a few isolated nodes and edges [34].

CClloosseellyy ccoonnnneecctteedd wwoorrkk

o Multidimensional separation of concerns (MDSOC)

According to Ossher and Tarr [28], MDSOC differs from AOP in that it supports

integration of multiple models, not just aspects augmenting the underlying language.

AspectJ does not support multiple models; all aspects in a system are coded relative to

the same model. Hyper/J [48], on the other hand, is a language which incorporates

multiple models. Hyper/J allows a developer to compose a collection of separate

Page 33: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 21 -

models, called hyperslices, each encapsulating a concern by defining and

implementing a (partial) class hierarchy appropriate for that concern. The models

typically overlap, and might or might not cut across one another.

o Reflection and Metalevel programming

A reflective system gives control over the underlying language’s semantics and

implementation. Such a system can be used as a tool for introducing aspects [2].

o Program transformation

The goal of program transformation is to write correct programs in a higher-level

language and transform it to a lower level language. This means that there may be

aspects described in a higher level language [2].

22..99.. SSiimmiillaarr rreesseeaarrcchh

Here we present research works that are closely related or similar to the work in this project.

We have found four such projects:

a. Refactoring of a legacy middleware system

Zhang and Jacobsen [12] showed in their study of a legacy implementation, that the

middleware architecture was greatly hindered by the ubiquitous existence of tangled code.

They were able to factor out part of the tangled code to aspects. Finally they applied software

engineering metrics to quantify the changes of the re- factored system for structural

complexity and runtime performance. They found that aspect oriented programming is

capable of composing orthogonal design requirements. The final woven1 system was able to

provide both the fundamental functionality and the aspect functionality with negligible

overhead and a leaner architecture. The configurability of the middleware was dramatically

increased because the features implemented in aspects could be configured in and out during

compile-time.

1 A woven system is the system after the regular code has been interleaved with the aspect code.

Page 34: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 22 -

b. Restructuring the FreeBSD operating systems

Coady and Kiczales [30] explored how aspects could have been used in the development of

the FreeBSD operating system, which had more than doubled in size between version 2 and

version 4. They introduced aspects to parts of the version 2 code, and then rolled them

forward to version 4. They found four key factors where AOP facilitated the software’s

evolution.

o Changes were better localized

o Configurability was more explicit

o Redundancy was reduced

o Extensibility aligned with an aspect was more modular

c. Comparing OOP with AOP

Mickelsson [42] compared AOP with OOP when implementing a distributed, web-based

application in terms of amount of code and time used. The two implementations had quite

similar results in terms of code statistics. However, the more generic services that are

implemented into aspects, the bigger the code advantage for AOP. He concluded that the AOP

implementation was more modular and reusable, and more flexible for future changes to

design and code. It was further concluded that good development tools are lacking for AOP

compared to OOP, especially for refactoring and UML-modelling.

We have compared the studies described above with our study in how they are similar and

how they differ. The results can be seen in Table 1.

Project Similarities Differences

a. Refactoring of a legacy

middleware system

Restructures a premade system

Studies the effects

Does not focus on readability

b. Restructuring the

FreeBSD operating systems

Restructures a premade system

Studies the effects

Reimplements from scratch

Does not focus on readability

c. Comparing OOP with Compares OOP solution with System made from scratch

Page 35: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 23 -

AOP AOP solution

Code statistics are used in

evaluation

Does not focus on readability

Table 1 Comparing our study with previous studies.

22..1100.. RReeffaaccttoorriinngg

The goal of refactoring and restructuring the code with aspects is the same. We want to

improve the code without altering the functionality of the system [29]. In addition we do not

want to rewrite the whole code; we just want to correct what we consider as poor code.

Some examples of refactorings are removing unused variables, removing unused methods and

removing duplicated code. Integrated development environments (IDE), like IntelliJ and

Eclipse support some refactorings.

We see two related questions that are important, but that will not be answered in this project:

1. Is refactoring a better method for improving the code than restructuring it with AOP?

2. Is refactoring a step that should be done when restructuring with AOP?

The key difference between refactoring and AOP is that with refactoring we can not remove

all duplicated code because it may be scattered around in objects that are not related.

22..1111.. SSyysstteemmss ttoo bbee eexxpplloorreedd

In this section we give a short introduction to the two systems to be explored. We will

comment further on these systems in relation to aspects later in the report.

Page 36: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 24 -

TThhee IIrraaqqii wwaarr

This system is relatively small and is originally given as an exercise in the elementary

programming course given at NTNU. We consider this system for two reasons:

1. This was the only system from the course exercises that had crosscutting concerns,

and as such was the only one that was suited for being restructured with aspects. This

is mainly explained by the small sizes of the exercise systems, which makes it easy to

achieve good modularity with regular OOP.

2. The exercise is aimed at learning the students about inheritance and polymorphism.

Inheritance, like aspects, can be seen as quantification; as the original code has effect

in all the classes that inherit from the base class.

The system simulates a war between USA and Iraq with respective command centres and

units. A controller steers the simulation.

DDiiaass 22

The Distributed Intelligent Agent System ver. 2 (DIAS2) was created as a part of a diploma

thesis [9] by Anders Aas Hanssen and Bård Smidsrød Nymoen2. This system consists of 175

classes in eleven packages.

Central issues in this system are inter-agent communication, interoperability, dispatching and

disposing of agents. The interoperability factor allows vendors and agents with other

implementation languages than that of DIAS2 to interact with the system.

2 Their work is again founded on the work by Joar Øyen (1999). He created the first version of DIAS.

Page 37: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 25 -

Figure 4 The overall architecture of DIAS2

The conceptual construction of the architecture is showed in Figure 4. All the small faces in

this figure are different agents. The architecture consists of seven main components which are

presented in Table 2.

Component Description

Agent Meeting Place (AMP) The place where the agents advertise their

capabilities and communicate with other agents.

CORBA Agent Meeting Place (CORBA

AMP)

Provides agents of other vendors or CORBA

clients to invoke methods in the AMP.

Workspace The places where a group of people have access

to common application, files, etc.

Agent

Page 38: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 26 -

Agent Docking Place The place where client agents reside. This is a

local workspace for a client.

Agent Performs tasks on behalf of a user or another

agent

Repository Where information and data is stored

CORBA client A program that needs to use CORBA to be able

to interact with DIAS II.

Table 2 The main components of the DIAS 2 system.

To implement this architecture different technologies are used:

Java is the programming language which is used to implement the architecture.

Aglets are event-driven java-based internet agents with persistence support. In the system

Aglets are used to implement the Agents, the workspaces, the ADPs and the AMPs.

JatLite’s KQML-package is used as communication language between the agents.

XML is the data format that is used to represent the knowledge in the system.

MASIF, written by OMG, is followed as a standard. The main goal for MASIF is

interoperability between agent systems as its main goal.

OrbixWeb is A Object Request Broker (ORB) from Iona used for CORBA communication.

We will not go into further details on how DIAS2 is implemented. The information presented

above is given in order to give a perspective of what kind of system we are refactoring in our

project.

Page 39: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 27 -

CChhaapptteerr 33.. RReesseeaarrcchh aaggeennddaa

In this chapter we present a background for our problem domain and how this affects our

possible research methods. In addition we present our overall work plan.

33..11.. RReesseeaarrcchh mmeetthhoodd

In this section we discuss and choose our research methods.

BBaacckkggrroouunndd ffoorr cchhooiiccee ooff rreesseeaarrcchh mmeetthhoodd

AOP is a relatively new domain of research, but has been shown great global interest in the

last few years. However, there have not been shown much interest in Norway, neither at the

universities and, to our knowledge, nor in the industry. Our partner, Telenor Mobile, has only

used AOP for a short period of time and not extensively.

The amount of research reports available, together with the nonexistent knowledge base at

NTNU, are important factors when choosing a method for research. When also considering

the problem definition, available time and resources, the possible methods are reduced.

PPoossssiibbllee rreesseeaarrcchh mmeetthhooddss

Due to the given context, a quantitative study is hard to conduct. A case study in cooperation

with one or more companies has to be ruled out. A possible study is a controlled experiment

with a group of students. This requires a relatively small system to study.

Page 40: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 28 -

A qualitative study is easier to accomplish. This is not to say that we can not focus on

quantitative measures, but we can not make general conclusions.

OOuurr cchhooiiccee

We chose to do an explorative study of the impacts of introducing aspects to a medium size

system with focus on readability. The main reasons why we chose this instead of doing a

controlled experiment were:

1. We wanted to study a system of some size, too big to restructure in a couple of hours. A

small system would not offer enough readability challenges since complexity and size are

the main causes for decreased readability.

2. We believed that it would be too time consuming to teach and demonstrate AOP to an

experiment group. The quality of teaching would also be a considerable source of

uncertainty, together with the experiment group’s interest and motivation for the subject.

3. We wanted to know if it is possible to increase readability, not if AOP always will do so.

Thereby we did not need to invest in an expensive quantitative study.

To support our study, we chose to use code metrics, comparing the new system with the one

we started with.

We discussed two applications in our prestudy. The main focus was on the second system,

DIAS 2. The “Iraqi war” is just a small example to emphasize the choice between inheriting

and separating out to an aspect.

33..22.. OOvveerraallll wwoorrkk ppllaann

For the study of DIAS 2, we followed two parallel paths. The first consisted of finding the

metrics, methods and tools for evaluating the system. The second path involved altering the

system. Some of the steps were done for both paths, as illustrated with the work plan in

Figure 5. The work plan is an approximation to the chronological order of our work

Page 41: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 29 -

Figure 5 Work plan for our study of DIAS 2.

Explanation of the steps in Figure 5:

Decide on technology means choosing programming language and support tools like

integrated development environments (IDE) and metrics tools.

Find methods for identifying crosscutting concerns 3 is a twofold task. First, explore

methods described in a previous research report [6]. Thereafter, see if there are other methods

for identifying aspects that have not been described in previous research.

Find attributes or metrics for evaluating the system is based on Goal-Question-Metrics

(GQM) [56] [64]; starting out with our problem definition and end up choosing metrics.

Study the system at hand means studying the documentation and code of the system.

Search for concerns to move out in aspects means using the methods found to find possible

candidates in the system.

3 The crosscutting concerns will be moved out to aspects as described in the Prestudy.

Decide on technology

Find methods for identifying

crosscutting concerns

Study system at

hand

Search for concerns to move

out in aspects

Implement the

changes

1. path: Finding methods for the study

2. path: Study and alter the actual system

Find attributes or metrics for evaluating

the system

Evaluate the

system

Page 42: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 30 -

Implement the changes is the coding of the new aspects, removing the redundant code and

testing the new code.

Evaluate the system means applying the metrics from GQM, validate, discuss and conclude

on them.

Page 43: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 31 -

CChhaapptteerr 44.. MMeettrriiccss ffoorr eevvaalluuaattiinngg

rreeaaddaabbii lliittyy

In this chapter we will elaborate on the metrics chosen for evaluating the system. In Figure 6

this task is highlighted in the work plan.

Figure 6 The step of finding metrics highlighted in the work plan.

Our hypothesis is that by using aspects, we can improve the readability of the code. This

should result in improved maintainability and less inconsistencies in the code. By using the

GQM process [56] [64] we have defined the following subgoals for readability:

o Reduced size of code

o Reduced code complexity

o Improved code structure

o Improved code documentation and comments

The last subgoal is disregarded for this study, since improved code documentation and

comments are independent of introducing AOP.

Decide on technology

Find methods for identifying

crosscutting concerns

Study system at

hand

Search for concerns to move

out in aspects

Implement the

changes

1. path: Finding methods for the study

2. path: Study and alter the actual system

Find attributes or metrics for evaluating

the system

Evaluate the

system

Page 44: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 32 -

To explore the subgoals we define the questions presented in Figure 7.

Figure 7 The transition from goal to question using GQM.

To answer the questions we will use the metrics presented in Figure 8.

Figure 8 The metrics used to answer the GQM questions.

Readability

Size

Complexity

Structure

Has the size of the system been reduced?

Has the complexity of the system been reduced?

Has the structure of the system improved?

GGooaall QQuueessttiioonn

Has the size of the system been reduced?

Has the complexity of the system been reduced?

Has the structure of the system improved?

QQuueessttiioonn MMeettrriicc

Lines of code

Coupling

Fan- in/Fan-out

Cohesion

Weighted methods per class

Hidden concerns

Page 45: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 33 -

We elaborate the metrics from Figure 8 like this:

o Number of lines of code will be measured by using Metrics 1.3.4 [35], a metrics plug-

in for the integrated development environment (IDE) Eclipse [47]. By removing code

tangling and scattering, we hope to be able to reduce the amount of code in the system.

There are several ways of measuring code size. We have decided to focus on code

lines within methods. This is both due to the choice of tool support and that all actions

in Java programs take place in methods.

o Using Metrics 1.3.4 we can measure afferent and efferent coupling. Aspects can make

core classes and packages independent, but is likely to increase coupling between core

classes and aspects. The justification of this trade-off is that core classes are code that

is likely to be reused [43].

o Using J Style 5 [54], an automated Java code review tool, we can measure fan-in, fan-

out, and Henry’s and Kafura’s fan-in/fan-out complexity. In Henry’s and Kafura’s

complexity metric we have used lines of code as the measure of length.

o Lack of Cohesion of Methods is measured in Metrics 1.3.4 by using Henderson-

Sellers method [7] [35]. In spite of the criticism presented in the prestudy, we will use

this metric since aspects can make classes and packages responsible for fewer tasks.

o Weighted Methods per class (WMC) are measured by using Metrics 1.3.4. By moving

crosscutting functionality to aspects, we hope to get modular, encapsulated units for

separate functionality [43].

o Measuring the amount of hidden concerns moved to aspects will be counted manually

[6]. We will move as much as possible of the supporting functionality to aspects

dedicated to their particular function.

Metrics disregarded for this study:

o McCabe’s Cyclomatic Complexity: This metric is left out because it weighs non-

nested and nested loops equally.

Page 46: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 34 -

o Depth of Inheritance Tree and Number of Children: We have chosen not to include

DIT and NOC, because our system does not contain the kind of inheritance needed to

observe changes in these metrics.

o Response For Class: Unfortunately, the tools we have available doesn’t offer this

metric.

Neatness of code is a system property; describing how well written and well arranged it is.

We have no means to measure this property, so we will have to disregard it for this study. The

original code was also very tidy, so any significant improvements were not to be expected.

We used the Jalopy Code Formatter 0.2.6-tool to remove any differences in code format

between the old and the new implementation [55].

We will use the measured results from the old and the new system as guidelines to evaluate

the hypothesis.

Page 47: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 35 -

CChhaapptteerr 55.. DDeecciiddee oonn tteecchhnnoollooggyy

In this chapter we discuss which programming languages and development tools we have

chosen.

Figure 9 The task of deciding on technology highlighted in the work plan.

55..11.. PPrrooggrraammmmiinngg llaanngguuaaggeess

BBaassee llaanngguuaaggee

The systems we have chosen to look at are both implemented in Java. Java is also the

language commonly used in student work at NTNU. In addition, we have mainly experience

with Java-programming.

Most AOP-languages have also been designed based on Java. By choosing Java as the base

language, we do not need to use valuable project time to master a new language.

Decide on technology

Find methods for identifying

crosscutting concerns

Study system at

hand

Search for concerns to move

out in aspects

Implement the

changes

1. path: Finding methods for the study

2. path: Study and alter the actual system

Find attributes or metrics for evaluating

the system

Evaluate the

system

Page 48: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 36 -

AAOOPP--eexxtteennssiioonn

There are several AOP-extensions for Java, both as languages and as frameworks. The two

most common and most evolved ones are AspectJ and AspectWerkz. Based on the work of

Yan Tu [46], we compared these two AOP-extensions to decide which best suited our project.

AspectJ AspectWerkz

Type Programming language Framework, based on XML, Java code and tagging Javadoc.

Time of weaving4 Compile time Compile time

Runtime

IDE Support Eclipse

Emacs

None

Usability >

Expressability >

Modularity >

Reuse of aspects <

Size of user community >

Software licence Apache licence BSD-style

Current development status Stable release, 1.1 Stable release, 0.81

Table 3 Comparison of AspectJ and AspectWerkz

For our project we deemed that the usability factor, along with better expressivity and

modularity, made AspectJ the better choice. Performance was not a priority, but AspectJ has

been measured to be as fast as or faster than AspectWerkz, depending on what mode

AspectWerkz is run in[46]. The ability to weave at runtime was not an option we needed. We

were concerned about AspectWerkz tendency to create its own form of code scattering

4 Weaving is the task of interleaving aspect code with regular code

Page 49: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 37 -

through tagging, and we did not feel comfortable with the alternative XML solution. For more

information on this matter, see [46]. Since AspectJ is also used by our partner, Telenor

Mobile, and have IDE support through Eclipse, this suited our needs better than

AspectWerkz.

55..22.. DDeevveellooppmmeenntt ttoooollss

We chose the open-source IDE Eclipse as our primary development tool [47]. We have used

this tool before; during earlier work at Telenor. Through plug- ins, Eclipse can support

refactoring tasks, the AspectJ language 5 and calculation of code metrics6. This makes Eclipse

a handy development tool for our project.

5 AspectJ is supported through the AJDT plug-in [57].

6 The Metrics 1.3.4 plug-in [35]

Page 50: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 38 -

Page 51: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 39 -

CChhaapptteerr 66.. IIddeennttiiffyyiinngg ccrroossssccuutttt iinngg

ccoonncceerrnnss

In this chapter we explain the methods we have used to find crosscutting concerns.

Figure 10 The tasks involved in identifying crosscutting concerns are highlighted in the work plan.

The task of identifying crosscutting concerns has been named ‘mining for concerns’ or in

short ‘aspect mining’ by Hanneman and Kiczales [6]. In their article, “Overcoming the

Prevalent Decomposition in Legacy Code”, they have described two methods; text-based

analysis and type-based analysis.

When searching for aspect mining methods we focused on simplicity. We wanted to find a

method that was easy to learn and to use. This was a phase of trial and error, and we tried four

different methods:

1. Search through system documentation

2. Search for frequently used types in the code (type-based analysis [6])

3. Search for similar code blocks in the code (called copy n’ paste analysis)

4. Reading the code (text-based analysis [6])

Decide on technology

Find methods for identifying crosscutting

concerns

Study system at

hand

Search for concerns to move

out in aspects

Implement the

changes

1. path: Finding methods for the study

2. path: Study and alter the actual system

Find attributes or metrics for evaluating

the system

Evaluate the

system

Page 52: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 40 -

66..11.. AAnnaallyyssiiss ooff ssyysstteemm ddooccuummeennttaattiioonn

Figure 11 Equal sub trees in activity diagram of the Communicate method in two different classes in DIAS2.

MMeetthhoodd

Studying the system documentation is straight forward, but you are in the hand of the prior

developers. It’s what and how they have documented which determines the outcome of such a

study. The size of the documentation matters as well. Too little or no documentation at all

makes this an obsolete method. A lot of information poses the challenge of getting the

overview needed to be able to use the information effectively, and correctly.

There are no given guidelines for this method, but the main focus is on finding concerns. Such

concerns may be given as principles, or they might be found in diagrams. Interesting diagrams

can be UML diagrams, like sequence diagrams or activity diagrams.

When we find crosscutting concerns, we must ensure that these have been documented in the

way described. If there is a difference between the design document and the implementation,

we will in our project keep it as it was implemented.

Page 53: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 41 -

PPrraaccttiissee

Since the DIAS 2 system is a part of a master thesis, it is quite well documented7. The design

of many classes and methods is described in UML class diagrams and activity diagrams.

Activity diagrams turned out to be a good source for crosscutting concerns. Figure 11 shows

how parts of two different activity diagrams can be identical. We did not find class diagrams

useful for finding such concerns.

In the DIAS 2 report, the developers have described some fundamental principles like

communication, ontology of messages, localization and connection which also might be

crosscutting concerns, but this requires going through the code to understand how these are

implemented.

66..22.. TTyyppee--bbaasseedd aannaallyyssiiss

Figure 12 The Aspect Mining Tool v.0.6a [49] used on the original DIAS 2 code.

7 The authors have focused on documentation to support reusability [9].

Page 54: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 42 -

MMeetthhoodd

This method is based on the Aspect Mining Tool [49] seen in Figure 12. The vertical grey and

white lines represent classes. A long line indicates a class with many code lines. The

markings on the white lines indicate where an object of a specified class (type) is used. You

can analyse all the types used in the system this way, up to six types at the same time.

According to Hanneman and Kiczales [6], the method is suitable when you have many

differently named object of the same type. Note, however, that if the same type is used for

different purposes, this method will not be helpful. An example of this is the use of Object

which is super class for all Java classes and therefore can be used in many different situations,

e.g. when removing objects from a list.

PPrraaccttiissee

We checked all the types used in the program. Those types that were frequently used were

noted in a list of possible crosscutting concerns. To be sure that they actually were

crosscutting concerns, we needed to analyse the code as well.

Page 55: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 43 -

66..33.. CCooppyy nn’’ ppaassttee aannaallyyssiiss

Figure 13 Finding copy n' paste code with the CPD tool.

MMeetthhoodd

This method is based on the Copy n’ Paste Detector (CPD) which is an open-source tool. The

tool is part of a bigger open-source project named PMD. The goal for PMD is to support

refactoring [44].

What the tool does is that it finds code which is similar in two locations. It is not based on the

actual writing, but the tokens in the code, e.g. “while” and “if”. You can decide how many

tokens you want to compare.

To get hits with this method, occurrences of similar code has to be written almost equally, not

counting white spaces, comments8 and line shifts. You will not get hits when:

o Statements are written in different order.

o Different statements or types are used for the same task (e.g. looping constructs and

array types).

o Different names are used for the same variables.

8 Javadoc-comments are counted.

Page 56: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 44 -

PPrraaccttiissee

We found this tool useful for finding large code blocks that are equal. Such code blocks might

be hard to find by just reading the code.

66..44.. TTeexxtt--bbaasseedd aannaallyyssiiss

Figure 14 Code from DIAS 2 shown in the Eclipse v.2.1 IDE [47].

MMeetthhoodd

Text-based analysis can be more than just reading the code. An IDE like Eclipse [47], shown

in Figure 14, offers different tools to help you analyse the code. Searching can be made with

native or regular expressions, or on code constructs such as methods and fields.

Text-based analysis can be used under the whole process, as a way of finding concerns, and as

a way of checking the candidates found as results of the other methods shown above.

Page 57: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 45 -

Hanneman and Kiczales [6] observed that this method is not helpful if naming conventions is

not followed strictly in the code.

PPrraaccttiissee

Text-based analysis is not easily done without guidance, this being either the outcome of the

methods mentioned previously or known concerns like logging and security. Most of the

crosscutting concerns we found in DIAS 2 were such known concerns.

66..55.. GGeenneerraall eexxppeerriieenncceess ffrroomm tthhee aassppeecctt mmiinniinngg

Even though we have had little experience with programming aspects, we used much more

time mining for aspects than with implementing them. This has been confirmed in a study

done in Sweden in 2002 [42].

We did not follow any well-structured process when we searched for aspects, going back and

forth between different methods and implementing aspects. This was especially the case for

reading code and documentation, due to the large amount of information in those sources.

The results from the aspect mining are vital to be able to implement aspects, and thus possibly

reach the goal of increasing readability. The methods used are most importantly documented

to be able to use them in future work.

Page 58: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 46 -

Page 59: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 47 -

CChhaapptteerr 77.. IImmpplleemmeennttaattiioonn

Figure 15 The task of implementing aspects is highlighted in the work plan.

In this chapter we give a brief overview of the implementation work. For more information

about the AspectJ language, see the AspectJ website [36].

77..11.. TThhee IIrraaqqii wwaarr

We implemented only one aspect for this system. The aspect performed updates on registers

when a unit like a tank or a bomber was destroyed or a soldier was killed. Originally this

happened in the kill() method in each of those units.

Decide on technology

Find methods for identifying crosscutting

concerns

Study system at

hand

Search for concerns to move

out in aspects

Implement the

changes

1. path: Finding methods for the study

2. path: Study and alter the actual system

Find attributes or metrics for evaluating

the system

Evaluate the

system

Page 60: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 48 -

Figure 16 The original code in The Iraqi war

What we see in Figure 16 is an example of a crosscutting concern which we could call

“update register of the control centre”.

For this concern we can define an aspect with a joinpoint being the calling9 of the method

kill(). A pointcut is a set of joinpoints. In Figure 17 we have defined a pointcut which target

every calling of the method kill().

Figure 17 A pointcut in AspectJ defines a set of joinpoints.

This pointcut defines where we might want to execute something. An advice defines what we

which action we want to perform on defined pointcuts. Notice, however, that an advice in

AspectJ is not an advice in the general sense. The actions are to be executed; they are not

optional.

9 The calling is defined as the point in the code where a method is called. Differing between before and after the

method executes is done in an advice (See Figure 18).

Unit

Soldier Tank Bomber

controlCenter.removeUnit(this); System.out.println (controllCenter.getName () + " lost one unit"); controllCenter.bodycountsoldiers++;

Code in method kill() in Bomber, Tank and Soldier:

Inheritance

pointcut callingKill(): call(void kill());

Page 61: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 49 -

Figure 18 An advice defines what actions take place at defined pointcuts.

In Figure 18 we have defined a pointcut which executes after the method kill() is executed.

The advice updates the register of units and then decreases the count for the given unit.

Figure 19 shows how Eclipse supports finding the locations where we have introduced

pointcuts. On the left side of the figure we can see the same advice as in Figure 18, though in

a Norwegian version. The after-advice we have defined advises on four locations which can

be seen in the list in the figure. Clicking on the elements in the list will lead us to where we

crosscut the code10.

At the location where we crosscut there is also a mark to the left of the code showing that

there is a specific advice which crosscut the code.

Figure 19 Support for readability in the Eclipse IDE provided by the AspectJ

plug-in.

10 A joinpoint is the location where we crosscut the code.

after(Unit unit): callingKill () && target(unit) {

controllCenter.removeUnit(unit);

controllCenter.decreaseBodyCount(1, enhet); }

Page 62: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 50 -

Note that the code of this particular aspect could have been executed in a method in the super

class Unit instead of in an aspect. If we had done this, we would not have needed to use

aspects; because there are no crosscutting concerns.

The code of this system is in Appendix C.

77..22.. DDIIAASS 22

PPrreeppaarriinngg tthhee ssyysstteemm

Before restructuring this code we made some alterations:

1. We formatted the code11 to make the differences between our coding style and the one

used originally as small as possible.

2. We removed some test code that could not be compiled because of errors.

The alterations were done in order to make the systems before and after applying aspects

more comparable.

CCooddee mmooddiiff iiccaattiioonnss iimmpplleemmeenntteedd

We have found crosscutting concerns by using all the methods described in Chapter 6.

We have summarized the ways we have restructured the system in Table 4. This table shows

the following information:

o The aspects we have introduced

o Descriptions of the crosscutting concerns

o Which methods we have used to identify the crosscutting concerns

o The original placements of the crosscutting code

11 The tool we used for formatting was Jalopy Code Formatter v.0.2.6 [55], a plugin for the Eclipse IDE.

Page 63: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 51 -

Name of aspect Description of concern Result of method (*) Original

placement

ExceptionPrinter Printing of message whenever errors of certain types occur. The messages include placement and type of exception.

Logging is a known concern from articles. Also based on information from type-based analysis.

In catch-blocks.

XmlDocumentUtils Creation of a treewalker which can traverse a tree of XML-code. The aspect also includes methods for getting out information from the tree.

Type-based analysis.

In many different classes and methods

StrictCommunication All agents but system agents need to ensure that certain properties are fulfilled before a message can be communicated.

Analysis of system documentation

In the communication method of the super class Agent

CheckMessageSameKQML Check if message is of type KQML which is the one used in DIAS, before actually handling the message.

Text-based analysis, left out of design documents.

In public methods handling received messages

AccessControl Accessing the system based on user information given by the system.

Text-based analysis (coincidental)

In main() methods

AgentCreation The general protocol all agents follow when an agent is created.

Security is a known concern from articles.

In method onCreation() in different agents

AgentsModelDebugging Logging of inserting new values into specific tables.

Copy n’ paste analysis

In insert() methods of table models

Page 64: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 52 -

ContextEventLogger Logging of context events in classes of type ContextAdapter which are used to start DIAS 2 applications.

Copy n’ paste analysis

In public methods in ServerApp class.

HandleMessaging Handles general procedures in agents that are followed when messaging.

Copy n’ paste analysis

In handleMessage() methods in different agents.

* Text-based analysis has been used as main or support method for all.

Table 4 Implementation of crosscutting concerns in DIAS 2

The code for the aspects is given in Appendix D, while the code for the whole system can be

found on the enclosed CD.

We could possibly have implemented more aspects, but we decided to end the implementation

period since we were running out of time.

IInnttrroodduucciinngg nneeww pprrooppeerrttiieess

We have shown in the example for The Iraqi War how an ordinary AspectJ aspect is

implemented. AspectJ offers another way of introducing new properties to an object. We can

introduce new fields, new methods and inheritance. Even introducing properties and methods

on interfaces are allowed.

The introduction of new properties in interfaces makes the Java program support multiple

inheritance. There are some limitations though. No naming conflicts are allowed. You may

not introduce new properties of the same type if it has the same name as properties in the base

code or inherited code.

Page 65: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 53 -

We have used introduction of fields and methods in an interface in the XmlDocumentUtils

aspect. Then we made several classes inherit this interface. Figure 20 shows the code where

this is done.

Figure 20 Introduction of properties to an interface and introducing that

interface to classes

We can see in Figure 20 that we have introduced the field diasDTD and the method

getXmlDocument on the WalkTree interface. Then we have made the ADPManagerAgent

class inherit this interface.

TTeessttiinngg tthhee ssyysstteemm

The goal for the testing is to ensure that we have preserved the functionality of the original

system. We have performed testing in the following ways:

1. Code reading

2. Following the test plan for the original project.

… public aspect XmlDocumentUtils { interface WalkTree {} public DiasDTD WalkTree.diasDTD = new DiasDTD(); /** * XML-document from a string formed correctly as XML * @param tree contains the XML-tree * @param withDTD if the XML-tree is sent with DTD * @return the tree as XML-document */

public XmlDocument WalkTree.getXmlDocument(String tree, boolean withDTD) {

try { StringReader strRead = new StringReader(tree); InputSource in = new InputSource(strRead); return XmlDocument.createXmlDocument(in, withDTD); } catch (SAXException e) { } catch (IOException e) { } return null; }

… declare parents: ADPManagerAgent implements WalkTree;

}

Page 66: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 54 -

See the DIAS 2 master thesis [9] for the original test plan and results. We obtained the same

test results with the restructured system as with the original system. The system is

functionally unchanged after restructuring with aspects.

Page 67: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 55 -

CChhaapptteerr 88.. RReessuullttss

Based on the Goal Question Metrics (GQM) [56] [64] analysis we have done, we have chosen

metrics within three specific areas; code size, complexity and structure. The measurements

have been done with software tools [35] [54] or done manually. Except for in lines of code,

we have left generated classes out of the analysis.

88..11.. CCooddee lliinneess wwiitthhiinn mmeetthhooddss

0

1000

2000

3000

4000

5000

6000

7000

8000

9000

Aspect code 183

Java code 4661 3833

Generated code 3159 3159

Original source Edited source

Figure 21 Code lines within methods.

What Figure 21 shows is that we have reduced the total amount of code lines by 8.27 percent.

The overall result is affected by the fact that approximately 40 percent of the code lines in the

Page 68: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 56 -

original source are generated by an external compiler12. If we do not count those generated

files we have removed 16.12 percent of the code.

The code is divided into different packages as shown in Figure 22. All the aspect code is

placed in the no.ntnu.dias.aspects package. 110 of 111 classes in no.ntnu.dias.amp.orb are

generated.

0 500 1000 1500 2000 2500 3000 3500

no.ntnu.dias.adp

no.ntnu.dias.agent

no.ntnu.dias.agent.participationAgent

no.ntnu.dias.agent.systemAgent

no.ntnu.dias.agent.userAgent

no.ntnu.dias.agentPlaceRegister

no.ntnu.dias.amp

no.ntnu.dias.amp.orb

no.ntnu.dias.diasDTD

no.ntnu.dias.KQML

no.ntnu.dias.util

no.ntnu.dias.aspects

Edited sourceOriginal source

Figure 22 Code lines within methods by package.

Figure 22 shows that we have reduced the amount of code lines in almost all packages.

88..22.. CCoommpplleexxiittyy

There are several complexity metrics to choose from. The ones we have chosen are based on

connections between modules.

12 The code generation is done by Orbixweb server software to handle CORBA communication.

Page 69: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 57 -

CCoouupplliinngg

We have used two different coupling metrics. They are substitutes for a clean coupling count.

We have not found any tool that offers a simple coupling metric on an object level.

Notice that the tool we have used to measure coupling cannot parse AspectJ source, meaning

that the couplings in those files have been counted manually.

Afferent coupling

Afferent coupling is a measurement of how many classes outside a package that depends on

classes inside the package.

Table 5 Measures of afferent coupling

The mean value for the afferent coupling is unaffected by the introduction of aspects while the

max value is increased. The reason for the increase is that we have added aspects which use a

particular superclass in addition to existing use. In DIAS 2 all agents inherits an Agent class,

which therefore is used by the new aspects.

Efferent coupling

Efferent coupling is a measurement of the number of classes inside a package that depend on

classes outside the package.

Afferent coupling Mean Std.dev Max Original source 9 8,29 28 Edited source 9 9,046 32

Page 70: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 58 -

Table 6 Measures of efferent coupling.

The decrease in efferent coupling is 8.31 percent between regular java classes in the original

and edited source.

FFaann-- iinn aanndd ffaann--oouutt

As stated in section 2.2, there is a correlation between coupling and fan- in/fan-out.

Fan-in

Table 7 Measures of fan-in.

The fan- in numbers shows a slightly different result than with afferent coupling. The mean

value for fan- in increases, while the standard deviation decreases.

Fan-in Mean Std.dev Max Original source 3,48 5,49 25,00 Edited source 3,54 5,13 25,00

Efferent coupling

Mean Std.dev Max

Original source 15,723 32,017 116

Edited source 14,417 30,785 116

Page 71: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 59 -

0

0,5

1

1,5

2

2,5

3

3,5

4

4,5

5

Aspect code Java code

Mea

n Fa

n in

Fan in

Figure 23 Distribution of fan-in of edited source.

We see from Figure 23 that the aspect code is the major contributor for the high fan- in count.

Fan-out

Table 8 Measures of fan out.

The fan-out count shows the same trend as efferent coupling does. This count decreases by

12.3 percent.

Fan-out

Mean Std.dev Max

Original source 14,08 10,66 59,00

Edited source 12,35 10,54 59,00

Page 72: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 60 -

Henry's and Kafura's fan-in/fan-out complexity

We have used code lines within methods for LOC in the formula “C = (Fan in + Fan out)2 ×

LOC” which is used to calculate Henry’s and Kafura’s Complexity.

Table 9 Measures of Henry's and Kafura's complexity based on LOC.

The decrease in this complexity count is as much as 41.05 percent dominated by the high

difference in the amount of code lines.

88..33.. SSttrruuccttuurree

Structure is connected to complexity on a module level, stating that the total complexity in a

module should be within certain limits. The second condition for a good structure is strong

cohesion within modules.

WWeeiigghhtteedd MMeetthhooddss ppeerr CCllaassss ((WWMMCC))

According to Sommerville [50], the higher counts we get for WMC, the more complex the

objects are.

Henry’s and Kafura’s complexity

Mean Std.dev Max

Original source 77720 215536 1408428

Edited source 45818 138027 945624

Page 73: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 61 -

0

5

10

15

20

25

Original source Edited source

Std.dev

Mean

Figure 24 Mean and standard deviation values for Weighted Methods per

Class (WMC)

Figure 24 show that both the mean value of WMC and the standard deviation decreases in the

edited version of DIAS 2. The decrease of the WMC is 20.12 percent.

CCoohheessiioonn

What we have measured is the lack of cohesion with Henderson-Seller’s method [7] [35].

Table 10 Measures of Henderson-Sellers’ lack of cohesion of methods.

We have a 6.05 percent decrease in lack of cohesion.

Lack of cohesion of methods Total Std.dev Max

Original source 0,424 0,493 0,990

Edited source 0,398 0,479 0,989

Page 74: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 62 -

HHiiddddeenn ccoonncceerrnnss

There is no guideline to fo llow when counting hidden concerns. The simple solution we have

chosen is to count how many aspects that are made; which is nine. See Chapter 7 for more

information about the aspects implemented.

88..44.. RReeaaddaabbiilliittyy

Readability

Lack of cohesion

Efferent coupling

Afferent coupling

Fan inFan out

Henry's and Kafura's complexity

Weighted method per class

Original sourceEdited source

Figure 25 Radar plot of readability attributes

Figure 25 shows all the readability attributes in a radar plot. In the plot, the further away from

the center, the better is the result. By better, we mean a comparison of results, and not as an

absolut scale.

Page 75: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 63 -

CChhaapptteerr 99.. DDiissccuussss iioonn

In this chapter we discuss the results we have obtained. Our results are also compared to

results from other studies [12] [42].

The sections in this chapter are based on the goals from the GQM analysis. First we discuss

the subgoals; decreased code size, less complex code and better code structure. Then we

discuss the main goal; increased readability.

The original DIAS 2 system was made by students at NTNU as a part of their diploma thesis.

These properties of the system are important:

o The technologies used was new when implemented

o The goal of the system was not a commercial product

o The main goal for the system was to be a general structure for distributed intelligent

agents systems, thus supporting reuse.

o Design and system documentation was stressed, thus reducing complexity

o Response time and security was not given priority

The focus on a general structure and the choice of not focusing on response time and security

may have contributed to less crosscutting concerns in the original system. As described in

section 2.5, performance and security can be crosscutting concerns. The use of new

technology might affect the result in different ways. Not having made many changes to the

system, means not having many chances to introduce crosscutting concerns in the code. On

the other hand, there is a chance that the technology is not used efficiently; caused by lack of

experience. In effect, crosscutting concerns might be introduced.

The system contains little support functionality. Security has never been implemented because

of a compatibility conflict between Java v. 1.2 and Aglets. DIAS 2 does not include support

Page 76: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 64 -

for performance, such as caching. This has been done to concentrate more on the main goals

of the system.

Other methods for modifying the system than AOP could in some instances have improved

the system further. Refactoring could have given a reduction in code size, through inheritance

and removal of unused variables. These changes have not been done in order to have a fair

comparison between the original system and the AOP version. Only when refactoring has

been part of moving code to aspects has such code improvements been done. There are two

examples of significant improvements through inheritance that can still be done with the

system:

o There are three general information classes that are similar, which could have been

modified.

o There are three table model classes that are almost identical, but we could not move

them to aspects since that would have resulted in a naming conflict.

99..11.. CCooddee ssiizzee

When discussing the change in code size, we will not include the generated code. Thus we

have a 16.12 percent decrease in the editable part of the code. This is an important reduction

in code size.

There are several ways of measuring the amount of code lines, and we could have chosen

differently. Two other opportunities are to consider also commented lines or code lines

outside methods. As a considerable part of the removed lines are in methods, the other ways

of measuring would probably have resulted in a smaller reduction. We argue though that since

the lines leading to complexity are inside methods, we are right to choose code lines in

methods as our metric.

Zhang and Jacobsen [12] reported a 9 percent decrease in lines of code when doing a similar

study. They measured all code lines including comments. Mickelson [42] compared an AOP

Page 77: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 65 -

solution with an OOP solution and got a 7.3 decrease in code lines. He measured all lines

except commented lines. These results show the same trend as in our study.

Figure 26 Use of the ExcpetionPrinter aspect on the package level.

The reduced code size is mostly due to the removal of code scattering through moving

crosscutting concerns to aspects. The amount of code that was scattered across the system was

extensive, as illustrated in Figure 26.

99..22.. CCoommpplleexxiittyy

The results of the complexity measures afferent coupling and fan- in are inconsisent. They

should have shown the same trend, as fan-out and efferent coupling did.

CCoouupplliinngg

The values we collected from coupling are not accurate. We were unable to measure coupling

between Java-files and aspects. This means that the coupling values for the edited system

should be higher. This increase is the trade-off for reducing coupling between regular system

files, as seen in Figure 27.

Page 78: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 66 -

Figure 27 Coupling between objects in Java vs. Aspect program

From Figure 27 we can see that efferent coupling is expected to decrease and our results

confirm this. Zhang and Jacobsen [12] have measured a similar metric, albeit on an object

level. They have reduced efferent coupling by 3 per object, thus confirming our result.

What is missing in Figure 27 is a connection back to the object (base class) from where we

removed the code. This connection is not mandatory, but we often need to use information

about the base class. This is a source for increased afferent coupling, which we did not get.

Two likely reasons for this result are that the coupling is measured on a package level and that

the afferent coupling for the package containing aspects is low. This reasoning is supported

by the increase in the standard deviation.

FFaann-- iinn // ffaann--oouutt

Fan- in / fan-out are similar measures to coupling, but works on object level as opposed to the

package level. This can be seen in the similar results achieved with the different metrics as

well. Fan-in has slightly increased for the edited system which we expected, but did not get

for afferent coupling. The fan-out has been decreased as efferent coupling, and what was we

expected.

Original Java program Program restructured with aspects

Object connection

Aspect connection (pointcut) Objects Aspect

Page 79: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 67 -

The measure of fan- in/fan-out complexity is considerably reduced, highly influenced by the

reduced amount of code lines

99..33.. SSttrruuccttuurree

Structure indicates how well modules are organized internally.

WWeeiigghhtteedd MMeetthhooddss ppeerr CCllaassss ((WWMMCC))

We observed a 20.12 percent decrease in WMC. This indicates that the amount of complex

methods has decreased. This is a result of moving parts of the functionality out to aspects. It is

important to see this result in relation to the change in coupling. The value for WMC can be

easily manipulated by moving methods to other classes and couple them back again. As a

result you get improved WMC at the expense of increase in both afferent and efferent

coupling. However, our coupling results indicate that the value for WMC is a result of

genuine improvement in the code structure.

CCoohheessiioonn

The value for Lack of Cohesion was measured to be 6.05 percent less for the edited system.

As mentioned in Chapter 4, we are uncertain how useful this metric is when using Java. The

metric penalizes the proper use of getter and setter methods. That said, the observed decrease

is still an indication of that the cohesion inside classes has been improved.

99..44.. RReeaaddaabbiilliittyy

Looking at the numbers in isolation doesn’t tell us much about whether the system has

improved or not. The radar plot in Figure 25 tells us that most of the chosen readability

metrics have been improved. This overall improvement would indicate that the system has

become smaller, less complex and better structured, and as such easier to read and understand.

Page 80: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 68 -

On the other hand, we have introduced a new language. How much of a barrier will the new

language be for someone exploring the system code? Based on experiences from earlier

studies [42] and from our own experiences during this study, it will take little extra effort. The

differences between AspectJ and Java are small. There are only a few new keywords

introduced, and the syntax is for the most part the same. However, is important when

developing with AOP. It can be a difficult task to find out where a pointcut crosscut the

regular code without guidance.

Page 81: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 69 -

CChhaapptteerr 1100.. CCoonncclluuss iioonn

We have studied Aspect Oriented Programming and the impacts of implementing aspects with

AspectJ and Java as languages. By using the GQM process we have found research questions

and metrics to support them, and we can conclude that our study has been successful in

supporting our hypothesis. Our hypothesis is that we through AOP-restructuring can improve

the readability of an object-oriented system. In our study this system was DIAS 2 [9]. As

mentioned earlier we cannot generalize the results from our hypothesis13.

The success is supported by the following answers of the questions from the GQM analysis:

Has the size of the system been reduced?

The size of the system has been reduced.

Has the complexity of the system been reduced?

The overall complexity of the system has been reduced.

Has the structure of the system improved?

The structure of the system is better after restructuring.

Can restructuring an object-oriented system with aspects increase its readability?

We can conclude, based on the reduction in code size and lower complexity and better

structure, that the readability in DIAS 2 is increased.

13 We do not say that AOP-restructuring will increase readability for all OO systems

Page 82: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 70 -

Page 83: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 71 -

CChhaapptteerr 1111.. FFuurrtthheerr wwoorrkk

During our study of AOP we have found several areas of possible further work. This chapter

we give a short summary.

TTeecchhnniiqquueess ffoorr iiddeennttiiffyyiinngg ccrroossssccuuttttiinngg ccoonncceerrnnss

During our study we have noticed that there are few existing methods for finding crosscutting

concerns. We have found two methods in an article by Hanneman and Kizcales [6]. These

methods are type-based analysis and text-based analysis.

The tool [49] used in type-based analysis is no longer maintained according to the developer

Jan Hanneman. He has suggested two other tools which are Aspect Browser [58] which

provides lexical analysis and FEAT [59] which by using an abstract representation can help

you find crosscutting code.

The use of such tools and the process of identifying crosscutting concerns are possible

subjects for further work.

MMeettrriiccss aanndd AAOOPP

While measuring our system we found that the metrics intended for examining AOP-based

code was not well defined. Also, the tools we used didn’t support AspectJ which forced us to

count several metrics manually within the aspects. The study of metrics with AOP and

developing a metric tool that supports AspectJ is then possible further work.

Page 84: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 72 -

AAOOPP aanndd rreeffaaccttoorriinngg

As mentioned in our Prestudy, the goal of refactoring and restructuring with aspects is almost

the same. This in mind, a comparative study of those two methods can be the focus of future

work. The question could then be “Is refactoring a better method for improving the code than

restructuring it with AOP?”

Another question from our Prestudy is whether refactoring should be done when restructuring

with AOP.

RReeppeeaattiinngg oouurr ssttuuddyy iinn eemmppiirriiccaall oorr ccaassee ssttuuddyy

Our study of restructuring an object-oriented system can be extended to more formal

experiments or real- life case stud ies within companies.

UUssiinngg AAOOPP iinn rreessiilliieenntt ssyysstteemmss ddeevveellooppmmeenntt

The software development group WEBSYS [62] at the Department of Computer and

Information Science (IDI) at NTNU is researching web-based systems with the following

goal:

“The main objective of WEBSYS is to develop high-quality research competence and concrete

guidelines for the industrial development of timely and reliable Web-based systems.”

One sub-goal for WEBSYS is to study reliability vs. time-to-market. Using AOP under

development to enforce a robust architecture might be fruitful in such contexts.

TTeessttiinngg ooff aassppeeccttss

We have mentioned the use of aspects for testing purposes [18] in our prestudy. Unit testing

with JUnit for Java [61] and mock-up objects made with AspectJ is described in an article

[62] published at XProgramming.com.

Page 85: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 73 -

There has been limited development in the area of testing aspects, and this is therefore a

possible area of future research.

Page 86: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 74 -

Page 87: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 75 -

AAppppeennddiixx AA.. RReeffeerreenncceess

All web addresses have been confirmed not broken at the date indicated between

parentheses.

[1] Ravi Sethi, Programming languages: concepts and constructs. Addison-Wesley, 1996

[2] G. Kiczales, J. Lamping, A. Mendhekar, C. Lopes, J. Loingtier and J. Irwin. Aspect-

Oriented Programming. Proceedings of European Conference on Object-Oriented

Programming Finland. Springer-Verlag, 1997

[3] D. L. Parnas. On the criteria to be used in decomposing systems into modules. ACM

Press, 1972

[4] Oscar Nierstrasz. A Survey of Object-Oriented Concepts, chapter 1, pages 3--21. ACM

Press Frontier Series. Addison-Wesley, 1989

[5] J. Eder, G. Kappel, and M. Schrefl. Coupling and cohesion in object-oriented systems.

In Conference on Information and Knowledge Management, Baltimore, USA, 1992.

[6] Jan Hanneman and Gregor Kiczales. Overcoming the Prevalent Decomposition in

Legacy Code. Position paper for workshop on Advanced Separation of Concerns,

International Conference on Software Engineering (ICSE), 2001.

[7] JDepend, a Java Metrics tool. http://www.clarkware.com/software/JDepend.html

(30.10.2003)

[8] Editors, Ten emerging technologies that will change the world. MIT Technology

review, January/February 2001.

[9] Anders Aas Hanssen and Bård Smidrød Nymoen. Distributed Intelligent Agent System,

version 2. Diploma NTNU, 2000.

Page 88: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 76 -

[10] Robert E. Filman and Daniel P. Friedman. Aspect-oriented Programming is

Quantification and Obliviousness. In Proc. Workshop on Advanced Separation of

Concerns, OOPSLA 2000.

[11] Ozer Aydemir, Kamer Kaya, H. Özgür Tan and Aykut Ünal. Turkolog: A development

toolkit for Aspect Oriented Programming. Workshop Proceedings of the First Turkish

Aspect-Oriented Software Development Workshop, Bilkent University, Ankara, May

2003.

[12] Charles Zhang and Hans-Arno. Jacobsen. Quantifying Aspects in Middleware

Platforms. Department of Electrical and Computer Engineering and Department of

Computer Science, University of Toronto, 2000.

[13] Markus Voelter. Aspect-Oriented Programming in Java. JavaReport issue 12/99, SIGS

Publications.

[14] Mati Shomrat and Amiram Yehudai. Obvious or Not? Regulating Architectural

Decisions Using Aspect-Oriented Programming. Proceedings of the 1st international

conference on Aspect-oriented software development, The Netherlands, ACM Press,

2002.

[15] Anurag Mendhekar and Gregor Kiczales, John Lamping. RG: A Case-Study for Aspect-

Oriented Programming. Xerox Palo Alto Research Center, February 1997.

[16] John Viega, J. T. Bloch, and Pravir Chandra. Applying Aspect-Oriented Programming

to Security. Cutter IT-Journal, issue 2 2001.

[17] Marcelo Sihman and Shmuel Katz. Superimpositions and Aspect-oriented

Programming. The Computer Journal, British Computer Society, issue 46(5) 2003.

[18] Michael Kircher, Prashant Jain, and Angelo Corsaro. "XP + AOP = Better Software?" ,

XP2002 - eXtreme Programming and Agile Processes in Software Engineering.

Alghero, Sardinia, Italy, May 26-29, 2002

[19] G. Kiczales, T. Elrad, T. Aksit, K. Lieberherr and H. Ossher. Aspect-Oriented

Programming. Communications of the ACM 44(10), October 2001.

[20] G. Kiczales, T. Elrad, T. Aksit, K. Lieberherr and H. Ossher. Discussing Aspects of

AOP. Communications of the ACM 44(10), October 2001.

Page 89: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 77 -

[21] G. Kiczales, E. Hilsdale, J. Hugunin, M. Kersen, J. Palm and W. G. Griswold. An

Overview of AspectJ. In 15th European Conference on Object–Oriented Programming

(ECOOP 2001), Budapest, Hungary, June 2001.

[22] Ron Bodkin. Enterprise Aspect-Oriented Programming with AspectJ. New Aspects of

Security. LogOn Web Day, Lillestrøm, Norway, September 2003.

[23] F. Brooks. No silver bullet: Essence and accidents of software engineering. Computer,

20(4):10-19, April 1987.

[24] G. Kiczales. Interview with Gregor Kiczales. TheServerSide.com, July 2003.

[25] M. Pinto and L. Fuentes, M. E. Fayad and J. M. Troya. Separation of coordination in a

dynamic aspect oriented framework. Proceedings of the 1st international conference on

Aspect-oriented software development, The Netherlands, ACM Press, 2002.

[26] L. Bergmans and T. Aksit. Composing crosscutting concerns using Composition Filters.

Communications of the ACM 44(10), October 2001.

[27] K. Lieberherr, D. Orleans and J. Owlinger. Aspect-Oriented Programming with

Adaptive Methods. Communications of the ACM 44(10), October 2001.

[28] H. Ossher and P. Tarr. Using multidimensional separation of concerns to (re)shape

evolving software. Communications of the ACM 44(10), October 2001.

[29] Martin Fowler, Kent Beck, John Brant and William Opdyke. Refactoring: Improving

the Design of Existing Code. Addison-Wesley, June 1999.

[30] Yvonne Coady and Gregor Kiczales. Back to the Future: A Retroactive Study of Aspect

Evolution in Operating System Code. University of British Columbia, 2003.

[31] Webopedia: Online Dictionary for Computer and Internet Terms.

http://www.webopedia.com/ (28.10.2003)

[32] AccessSience: McGraw-Hill’s online encyclopaedia for science and technology.

http://www.accessscience.com/ (28.10.2003)

[33] Aspect-oriented Software Development. http://aosd.net (28.10.2003)

[34] Karl J. Lieberherr. Connections between Demeter/Adaptive Programming and Aspect-

Oriented Programming (AOP). http://www.ccs.neu.edu/home/lieber/connection-to-

aop.html (29.10.2003)

[35] Metrics 1.3.4, a metrics plug- in for Eclipse. http://metrics.sourceforge.net/ (30.10.2003)

Page 90: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 78 -

[36] AspectJ website. http://www.aspectj.com/ (02.11.2003)

[37] AspectWerkz website. http://aspectwerkz.codehaus.org/ (02.11.2003)

[38] JBoss website. http://www.jboss.org/ (02.11.2003)

[39] JAC website. http://jac.objectweb.org/ (02.11.2003)

[40] Nanning website. http://nanning.snipsnap.org/ (02.11.2003)

[41] Gail C. Murphy, Robert J. Walker and Elisa L. A. Baniassad. Evaluating Emerging

Software Development Technologies: Lessons Learned from Assessing Aspect-

Oriented Programming. IEEE Transactions on software engineering, issue 4/1999.

[42] Magnus Mickelsson. Aspect-Oriented Programming compared to Object-Oriented

Programming when implementing a distributed, web-based application. Department of

Information Technology, Uppsala University, 2002.

[43] Zakaria and Hosny. Metrics for Aspect-Oriented Software Design. The American

University in Cairo, Workshop on Aspect-Oriented Modeling, International Conference

on Aspect-Oriented Software Development, March 2003.

[44] PMD v.1.3 website. http://pmd.sourceforge.net (04.11.2003)

[45] Jennifer Orr. JavaWorld Editor’s Choice Awards 2003.

http://www.javaworld.com/javaworld/jw-06-2003/jw-0609-eca_p.html (05.11.2003)

[46] Yan Tu. Comparison between AspectJ and AspectWerkz. SE Research Seminar –

preparation for Master Thesis, Software Engineering Program,

School of Computer Science, Information Systems, and Telecommunications

DePaul University, October 2003.

[47] Eclipse website. http://eclipse.org/ (05.11.2003)

[48] Hyper/J website. http://www.research.ibm.com/hyperspace/index.htm (05.11.2003)

[49] Aspect Mining Tool v.0.6a website. http://www.cs.ubc.ca/~jan/amt/ (06.11.2003)

[50] Ian Sommerville. Software Engineering. Addison-Wesley, 2000.

[51] Sencer Sultanoglu. Software Measurement Page, Software Complexity.

http://yunus.hun.edu.tr/~sencer/complexity.html . Department of Computer Science &

Engineering, Hacettepe University, Turkey. (13.11.2003)

Page 91: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 79 -

[52] Arthur H. Watson and Thomas J. McCabe. Structured Testing: A Testing Methodology

Using the Cyclomatic Complexity Metric. Computer Systems Laboratory, National

Institute of Standards and Technology, Gaithersburg, September 1996.

[53] Sallie M. Henry and Dennis G. Kafura. Software Structure Metric based on Information

Flow. IEEE Transaction on Software Engineering, 7(5), September 1981.

[54] J Style 5 website. http://www.mmsindia.com (13.11.2003)

[55] Jalopy Code Formater 0.2.6 website. http://jalopy.sourceforge.net (13.11.2003).

[56] Victor R. Basili. Software Modelling and Measurement: The Goal/Question/Metric

Paradigm. Technical paper, Department of Computer Science, Maryland, 1992.

[57] AJDT AspectJ plug- in for Eclipse. http://www.eclipse.org/ajdt/ (18.11.2003)

[58] Aspect Browser. http://www.cs.ucsd.edu/users/wgg/Software/AB/ (18.11.2003)

[59] FEAT. http://www.cs.ubc.ca/~mrobilla/feat/ (18.11.2003)

[60] JUnit website. http://www.junit.org/ (18.11.2003)

[61] Simon Monk, Stephen Hall. Virtual Mock Objects using AspectJ with JUNIT,

10.01.2002, http://xprogramming.com/xpmag/virtualMockObjects.htm (18.11.2003)

[62] Websys group, IDI, NTNU. http://www.idi.ntnu.no/grupper/su/introduction.html

(18.11.2003)

[63] Edward V. Berard. Metrics for Object-Oriented Software Engineering.

http://www.toa.com/pub/moose.htm. The Object Agency, Inc., August 1998.

(25.11.2003)

[64] Rini van Solingen and Egon Berghout. The Goal/Question/Metric Method: A practical

guide for quality improvement of software development. McGraw-Hill Publishers,

1999.

Page 92: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 80 -

Page 93: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 81 -

AAppppeennddiixx BB.. GGlloossssaarryy

Adaptive programming Adaptive Programming (AP) is the special case of

Aspect-Oriented Programming (AOP) where some of the

building blocks are expressible in terms of graphs and

where the other building blocks refer to the graphs using

traversal strategies.

ADP Agent Docking Places, the place where client agents

reside in the DIAS 2 system. This is a local workspace for

a client.

Advice An advice is used in order to define the behaviour of the

aspects.

Afferent coupling Afferent coupling is the number of classes outside a

package that depend on classes inside the package.

Agent Agents perform tasks on behalf of a user or another agent

in the DIAS 2 system.

AMP Agent Meeting Place, the place where the agents advertise

their capabilities and communicate with other agents in

the DIAS 2 system.

AMT Aspect Mining Tool, used to search for crosscutting

concerns.

AOP A style of programming that attempts to abstract out

features common to many parts of the code beyond simple

functional modules and thereby improve the quality of

Page 94: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 82 -

software.

Architecture The software architecture of a program or computing

system is the structure or structures of the system, which

comprise software elements, the externally visible

properties of those elements, and the relationships among

them.

Aspect Aspects are design decisions that are difficult to address

in actual code because they crosscut the system.

AspectJ AspectJ is a seamless aspect-oriented extension to the

Java programming language

AspectWerkz AspectWerkz is an AOP/AOSD framework for Java.

C++ Bjarne Stroustrup developed C++ as an extension of C in

1980’s at Bell Laboratories as an object-oriented

programming language.

Cohesion Cohesion is a software attribute representing the degree to

which the components are functionally connected within a

software module.

Composition filters The composition filter model can support basic object-

oriented constructs such as inheritance and delegation, as

well as database- like features such as dynamic data

structures, transactions, multiple views and associative

access exclusively via filters.

Copy n’paste analysis This method is based on the Copy n’ Paste Detector

(CPD). What the tool does is that it finds code which is

similar in two locations.

CORBA Common Object Request Broker Architecture, an Object

Management Group (OMG) specification which provides

the standard interface definition between OMG-compliant

Page 95: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 83 -

objects.

Coupling The degree to which components depend on one another.

CPD Copy n’ Paste Detector (CPD), an open-source tool. What

the tool does is that it finds code which is similar in two

locations. The tool is part of a bigger open-source project

named PMD.

Crosscutting concerns Properties or areas of interest in a system that can not be

cleanly encapsulated in a generalized procedure.

Cyclomatic complexity Cyclomatic complexity is a measure for the complexity of

code related to the number of ways there are to traverse a

piece of code.

DIAS Distributed Intelligent Agent System ver. 2. Central issues

in this system are inter-agent communication,

interoperability, dispatching and disposing of agents.

DIT Depth of Inheritance Tree, maximum inheritance path

from the class to the root class.

Eclipse The Eclipse Platform is an open extensible IDE that

provides building blocks and a foundation for

constructing and running integrated software-

development tools.

Efferent coupling Efferent coupling is the number of classes inside a

package that depend on classes outside the package.

Fan- in Fan- in is a measure of the number of functions that call

some other function (say X). A high value for fan- in

means that X is tightly coupled to the rest of the design.

Fan-out Fan-out is the number of functions which are called by

function X. A high value for fan-out suggests that the

overall complexity of X may be high due to the control

Page 96: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 84 -

logic needed to coordinate the called components.

FORTRAN FORmula TRANslation; high-level programming

language for mathematical and scientific purposes

GQM The Goal Question Metric paradigm is a mechanism for

defining and evaluating a set of operational goals, using

measurement.

Hidden concerns Hidden concerns are concerns not represented in the

current system decomposition, and as a consequence have

to be forced onto the primary decomposition.

IDE Integrated Development Environment

Java A platform-independent object-oriented programming

language

JDK Java Development Kit

Joinpoint Joinpoints are the locations which are affected by one or

more of the crosscutting concerns. Another way of

looking at this is that joinpoints are the locations where

we can hook on new actions before or after the original

code execution

JStyle 5 JStyle 5 is an automated Java code review tool

KQML Knowledge Query and Manipulation Language

Legacy system A computer system or application program which

continues to be used because of the cost of replacing or

redesigning it and often despite its poor competitiveness

and compatibility with modern equivalents.

LOC – lines of code LOC is measured as non-comment and non-blank lines

inside method bodies. LOC is a common measure of the

size or progress of a programming project.

Page 97: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 85 -

Metalevel Programming Metalevel Programming allows us to expose selected

aspects of the programming model

Metrics A measure of software quality which indicate the

complexity, understandability, testability, description and

intricacy of code.

MultiDimensional Separation of

Concerns MDSOC

Multi-dimensional separation of concerns is an approach

to separation of concerns, supporting simultaneous

encapsulation of all kinds of concerns in a software

system, overlapping and interacting concerns, and on-

demand remodularization.

NOC - Number of Children NOC is the number of immediate subclasses of a class in

the hierarchy.

Oblivious programmer An oblivious programmer does not need to expend any

additional effort to make some mechanism work.

OOP Object-Oriented Programming

PMD PMD scans Java source code looking for potential

problems.

Pointcut A pointcut is a program element that picks out join points,

as well as data from the execution context of the join

points. Pointcuts are used primarily by advice.

Program transformation The goal of program transformation is to write correct

programs in a higher- level language and transform it to a

lower level language.

Quantified statements Quantified statements are statements that have effect

many places in the underlying code.

Reflection A reflective system gives control over the underlying

language’s semantics and implementation.

Page 98: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 86 -

RFC - Response For a Class RFC is the number of all methods that can be invoked in

response to a message to an object of the class or by some

method in the class.

SDK Software Development Kit

Simula SIMUlation Language, a general-purpose object-oriented

application programming language. An extension to

ALGOL 60 for the Univac 1107 designed in 1962 by

Kristen Nygaard and Ole-Johan Dahl and implemented in

1964.

Smalltalk The pioneering object-oriented programming system

developed in 1972 by the Software Concepts Group, led

by Alan Kay, at Xerox PARC between 1971 and 1983.

Smalltalk took the concepts of class and message from

Simula-67 and made them all-pervasive.

Text-based analysis Text-based analysis is a way of identifying crosscutting

concerns through code reading.

The Iraqi War An exercise in the elementary programming course given

at NTNU

Type-based analysis Type-based analysis is based on the Aspect Mining Tool

and is used for identifying crosscutting concerns.

UML Unified Modelling Language

WMC - Weighted Methods per

Class

Weighted Methods per Class is the number of methods

included in a class weighted by the complexity of each

method.

XML Extensible Markup Language

Page 99: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 87 -

AAppppeennddiixx CC.. CCooddee ffrroomm TThhee IIrraaqqii WWaarr

In this appendix we present the code from the implementation of The Iraqi war restructured

with aspects. This system is implemented using Norwegian language in comments, variables

and system prints.

/** * Oppdaterer lister og tall i Overkommando etter at * en enhet er drept. * * @author Erlend Rønningen * @author Tore Steinmoen */ public privileged aspect FjernEnhetFraOverkommando { pointcut drep(): call(void Enhet+.drep()); public OverKommando Enhet.hentOverKommando() { return side; } after(Enhet enhet): drep() && target(enhet) { OverKommando side = enhet.hentOverKommando(); side.slettEnhet(enhet); side.endreBodyCount(1, enhet); } }

/** * interface Mekanisk * * Et interface for alle mekaniske enheter. * @author Danner * @version 1.0 final * @date 17.02.2003 */ public interface Mekanisk { /** * slitasje() kalles på alle mekaniske enheter en gang om dagen og er * til for å sjekke om enhetene bryter sammen. **/ public void slitasje(); }

Page 100: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 88 -

/** * Class Enhet * * En baseklasse for alle enheter i dens tore irakkrigen. * @author Danner * @version 1.0 final * @date 17.02.2002 **/ public abstract class Enhet { protected OverKommando side; protected int sektor; /** * hentSektor() returnerer sektren denne enheten befinner seg i. * **/ public int hentSektor(){ return sektor; } /** * * **/ public OverKommando hentSide() { return side; } /** * utfoerDagensHandling(OverKommando fiende) er en abstrakt metode * som er implementert forskjellig i alle baseklasser. * @param fiende ved metodekall må fienden identifiseres. **/ public abstract void utfoerDagensHandling(OverKommando fiende); /** * drep() dreper denne enheten, men akkurat hva som skjer i det enheten * dør er sub-implementasjonsspesifikt. **/ public abstract void drep(); /** * Konstructoren initialiserer enheten til å befinne seg i en * av sektorene i ørkenen. */ public Enhet(OverKommando side) { this.side = side; sektor = (int)(Math.random()*Simulator.ANTALL_SEKTORER); } }

import java.util.ArrayList; public class BombeFly extends Enhet implements Mekanisk{

Page 101: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 89 -

public BombeFly(OverKommando side) { super(side); sektor = -1; side.leggTilIEnhetsListe(this); side.leggTilIMekaniskListe(this); } public void drep() { System.out.println(side.hentNavn() + " mistet et fly!"); } public void slitasje(){ if(Math.random() < 0.05){ drep(); } } public void utfoerDagensHandling(OverKommando fiende){ // finne tilfeldig enhet å bombe. ArrayList kandidater = new ArrayList(); ArrayList venner = side.hentAlleEnheter(); ArrayList fiender = fiende.hentAlleEnheter(); for(int i = 0; i < venner.size(); i++) { kandidater.add(venner.get(i)); } for(int i = 0; i < fiender.size(); i++) { kandidater.add(fiender.get(i)); } int tilftall = (int)(Math.random()*kandidater.size()); Enhet bombemaal = (Enhet) kandidater.get(tilftall); // bomb målet System.out.println("Et bombefly fra " + side.hentNavn() + " bomber en enhet fra " + bombemaal.hentSide().hentNavn() + "."); bombemaal.drep(); } }

/** * Class Soldat * er en spesialisering av en Enhet i krigen vår. * Soldater løper rundt i ørkenen og skyter på fiendetroppene de kommer * over. * @author Danner * @version 1.0 final * @date 17.02.2003 **/ public class Soldat extends Enhet { Soldat(OverKommando side) { super(side); side.leggTilIEnhetsListe(this); } public void drep() { System.out.println(side.hentNavn() + " mistet en soldat"); }

Page 102: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 90 -

public void utfoerDagensHandling(OverKommando fiende){ Enhet fiendeEnhet = fiende.finnEnhetISektor(sektor); if(fiendeEnhet == null) { //flytt til ny sektor sektor = (int)(Math.random()*Simulator.ANTALL_SEKTORER); } else { //skyt på fiende fiendeEnhet.drep(); } } }

/** * Class Tanks er en spesialisering av en Enhet i krigen vår. * Tanks kjører rundt i ørkenen og skyter på fiendetroppene de kommer * over. * @author Danner * @version 1.0 final * @date 17.02.2003 **/ public class Tanks extends Enhet implements Mekanisk { protected boolean breakdown; Tanks(OverKommando side) { super(side); side.leggTilIEnhetsListe(this); side.leggTilIMekaniskListe(this); } public void drep() { System.out.println(side.hentNavn() + " mistet en tanks"); } public void utfoerDagensHandling(OverKommando fiende){ if(!breakdown) { Enhet fiendeEnhet = fiende.finnEnhetISektor(sektor); // skyt evt fiende. if(fiendeEnhet != null) { fiendeEnhet.drep(); } // er det ikke flere fiende-enheter, flytt videre. Enhet nyFiendeEnhet = fiende.finnEnhetISektor(sektor); if(nyFiendeEnhet == null){ sektor = (int)(Math.random()*Simulator.ANTALL_SEKTORER); } } } public void slitasje(){ breakdown = false; if(Math.random() < 0.05){ breakdown = true; System.out.println("En tanks fra " + side.hentNavn() + " bryter sammen"); } } }

Page 103: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 91 -

import java.util.ArrayList; /** * class OverKommando * * En overkommando er en klasse som styrer en side i den store irakkrigen. * Hver side holder på sine enheter og gir dem ordre. * * @author Danner * @version 1.0 final * @date 17.10.2003 **/ public class OverKommando{ protected ArrayList enheter; protected ArrayList mekaniskeEnheter; protected String navn; private int bodycountsoldater; private int bodycounttanks; private int bodycountfly; OverKommando(String navn, int soldater, int tanks, int fly) { enheter = new ArrayList(); mekaniskeEnheter = new ArrayList(); this.navn = navn; bodycountsoldater = 0; bodycountfly = 0; bodycounttanks = 0; for(int i = 0; i < soldater; i++) new Soldat(this); for(int i = 0; i < tanks; i++) new Tanks(this); for(int i = 0; i < fly; i++) new BombeFly(this); } /** * leggTilEnhetsListe(Enhet nyEnhet) * legger til en ny enhet inn under denne overkommandoen. * Alle enheter må ligge i denne listen. **/ public void leggTilIEnhetsListe(Enhet nyEnhet){ enheter.add(nyEnhet); } public void endreBodyCount(int endring, Object type) { if (type instanceof Soldat) { bodycountsoldater += endring; } else if (type instanceof Tanks) { bodycounttanks += endring; } else if (type instanceof BombeFly) { bodycountfly += endring; } else { System.err.println("----- Feil i type!!"); } } /** * public ArrayList hentAlleEnheter() returnerer alle enhetene under * denne overkommandoen. Egentlig burde man vel strengt talt lage en * klone av arraylisten, men... Pytt ;) **/ public ArrayList hentAlleEnheter() {

Page 104: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 92 -

return enheter; } /** * hentAntallEnheter returnerer hvor mange enheter som ligger under * denne overkommandoen. **/ public int hentAntallEnheter() { return enheter.size(); } /** * leggTilIMekaniskListe(Mekanisk nyEnhet) * legger en enhet til i mekaniskListe under denne enheten. Alle * mekaniske enheter er fort med i begge listene, men * denne metoden legger kun enheten til i mekanisk-listen. **/ public void leggTilIMekaniskListe(Mekanisk nyEnhet){ mekaniskeEnheter.add(nyEnhet); } /** * slettEnhet(Enhet slettes) * slettenhet fjerner enheten fra denne overkommandoen og dermed anses * enheten som død, og vil forsvinne. **/ public void slettEnhet(Enhet slettes){ enheter.remove(slettes); if (slettes instanceof Mekanisk) { System.out.println("--------- Mekanisk enhet slettes -----------"); mekaniskeEnheter.remove(slettes); } } /** * slettMekaniskEnhet(Mekanisk slettes) * sletter en mekanisk enhet fra mekanisk-lista til denne * overkommandoen. vil ikke slette enheten fra enhetslista. **/ public void slettMekaniskEnhet(Mekanisk slettes){ mekaniskeEnheter.remove(slettes); } /** * hentNavn() * returnerer navnet på denne Overkommandoen - eks "irak" eller "usa". **/ public String hentNavn() { return navn; } /** * skrivstatus() * Skriver ut status til denne overkommandoen **/ public void skrivStatus() { System.out.println("Status for " + navn); System.out.println("=============================================="); System.out.println("Soldater døde: " + bodycountsoldater); System.out.println("Tankser sprengt: " + bodycounttanks);

Page 105: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 93 -

System.out.println("Fly skutt ned: " + bodycountfly); } /** * finnEnhetISektor(int sektor) * vil returnere en enhet under denne overkommandoen som befinner seg * i sektoren gitt av innparameteren. **/ public Enhet finnEnhetISektor(int sektor) { ArrayList kandidater = new ArrayList(); for(int i = 0; i < enheter.size(); i++) { Enhet temp = (Enhet) enheter.get(i); if(temp.hentSektor() == sektor) { kandidater.add(temp); } } if(kandidater.size() == 0) return null; int tilftall = (int)(Math.random() * kandidater.size()); return (Enhet) kandidater.get(tilftall); } /** * angrip(OverKommando fiende) * angrip kalles en gang om dagen per overkommando, og sørger for at * alle enhetene til denne overkommandoen angriper, og at alle * mekaniske enheter blir slitt. * @param fiende Overkommandoen man vil angripe. **/ public void angrip(OverKommando fiende) { ArrayList enheterKlone = (ArrayList) enheter.clone(); for(int i = 0; i < enheterKlone.size(); i++) { ((Enhet)enheterKlone.get(i)).utfoerDagensHandling(fiende); } // sørge for at alle mekaniske enheter blir slitt etter dagens slutt. ArrayList mekaniskKlone = (ArrayList) mekaniskeEnheter.clone(); for(int i = 0; i < mekaniskKlone.size(); i++){ ((Mekanisk)mekaniskKlone.get(i)).slitasje(); } } }

Page 106: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 94 -

Page 107: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 95 -

AAppppeennddiixx DD.. CCooddee ffrroomm DDIIAASS 22

We only present the code in aspects of DIAS 2 in this appendix.

package no.ntnu.dias.aspects; import com.ibm.aglet.system.ContextAdapter; import com.ibm.awb.misc.Opt; import com.ibm.awb.security.AccessController; import com.ibm.aglet.system.AgletRuntime; import java.security.Identity; /** * @author Tore Steinmoen * * This is an accesscontrol for all the contextadapters in the project. * @see no.ntnu.dias.amp.AMP * @see no.ntnu.dias.amp.CorbaAMP * @see no.ntnu.dias.adp.ADP * @see no.ntnu.dias.adp.CorbaADP * @see no.ntnu.dias.util.ServerApp * */ public aspect AccessControl { final static Opt[] options = { Opt.Entry("-protocol", "maf.protocol", null), Opt.Entry("-username", "username", null), Opt.Entry("-password", "password", null), }; pointcut mainMethod() : execution(public static void main(..)); pointcut accessingClasses(): within(com.ibm.aglet.system.ContextAdapter+); /** * Controls if the main method is allowed to execute * Must be a legitimate user to be allowed * @param arguments arguments to the main method */ void around(String[] arguments) throws Exception : mainMethod() && accessingClasses() && args(arguments) { Opt.setopt(options); AgletRuntime runtime = AgletRuntime.init(arguments); if (checkUser(runtime) == null) { throw new Exception("User authentication failed."); }

Page 108: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 96 -

proceed(arguments); } /** * Checks if the user is registered with runtime * environment * @param runtime environment */ private Identity checkUser(AgletRuntime runtime) { String username, password; try { AccessController.beginPrivileged(); String DEFAULT_USERNAME =

System.getProperty("user.name"); username = System.getProperty("username",

DEFAULT_USERNAME); password = System.getProperty("password", ""); } finally { AccessController.endPrivileged(); } System.out.println("Authentification of user: \"" + username + "\""); return runtime.authenticate(username, password); } }

package no.ntnu.dias.aspects; import no.ntnu.dias.agent.Agent; import no.ntnu.dias.agent.userAgent.UserAgent; /** * @author Tore Steinmoen * * This aspect is responsible for certain general calls which * must be made on creation of different types of agents. * * @see no.ntnu.dias.agent.userAgent.UserAgent * @see no.ntnu.dias.agent.systemAgent.SystemAgent * @see no.ntnu.dias.agent.participationAgent.ParticipationAgent * * All the affected agents must define agentid and agentinfo * as well as call the agentCreation-method. * */ public privileged aspect AgentCreation { pointcut onCreation(Agent agent, Object object) : execution(* onCreation(Object)) && target(agent) && args(object); pointcut onCreationInUserAgent(UserAgent agent) : execution(* onCreation(Object)) && target(agent); /** * Concludes the creation of agents for general agents * @param agent the processing agent

Page 109: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 97 -

* @param init the arguments to the initiation * */ after(Agent agent, Object init) : onCreation(agent, init) { String className =

thisJoinPointStaticPart.getSignature().getDeclaringType().getName();

if (agent.originTypeOfPlace.equals("ADP") && agent.urlDSP.equals(agent.urlOriginPlace)) { agent.urlDSP = null; } agent.setAgentFeatures(); agent.setAgentProperties(); System.out.println(className + "::onCreation() The DSP is: " +

agent.urlDSP); agent.createAgentID(); System.out.println(className + "::onCreation() agentID : " + agent.agentID.toString()); agent.createAgentInfo(); System.out.println(className + "::onCreation() agentInfo : " + agent.agentInfo.toString()); agent.setPresent(); agent.setOrigin(); agent.register(agent.urlOriginPlace); agent.agentCreation(init); } /** * Concludes the creation of useragents * (in addition to the general procedure) * * @param agent processing agent */ after(UserAgent agent) : onCreationInUserAgent(agent) { agent.addListeners(); agent.connectedToDSP = agent.isConnected(); System.out.println("UserAgent::onCreation(): connectedToDSP is:

" + agent.connectedToDSP); } }

package no.ntnu.dias.aspects; import javax.swing.table.AbstractTableModel; /** * @author Tore Steinmoen * * A debugging class for table models * */ public privileged aspect AgentsModelDebugging { private boolean DEBUG = true; pointcut setValueAt(AbstractTableModel model, int row, int col,

Object value) : execution(* setValueAt(..)) &&

Page 110: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 98 -

target(model) && args(value, row, col); /** * Registers values before altering a table (model) * @param the model to be altered * @param row which row value is placed in * @param col which column valuse is placed in * @param value which value is inserting into the model */ before(AbstractTableModel model, int row, int col, Object value) : setValueAt(model, row, col, value) { if (DEBUG) { System.out.println("Setting value at " + row + ","

+ col + " to " +value + " (an instance of " + value + ")");

} } /** * Prints the table after altering the table (model) * @see AgentModelDebugging#printDebugData * @param model the model which is altered */ after(AbstractTableModel model) returning: setValueAt(model, int, int, Object) { if (DEBUG) { System.out.println("New value of data:"); printDebugData(model); } } /** * Prints all the values in table (model) * @param model the model with the values */ private void printDebugData(AbstractTableModel model) { int numRows = model.getRowCount(); int numCols = model.getColumnCount(); for (int i = 0; i < numRows; i++) { System.out.print(" row " + i + ":"); for (int j = 0; j < numCols; j++) { System.out.print(" " + model.getValueAt(i,j)); } System.out.println(); } System.out.println("--------------------------"); } }

package no.ntnu.dias.aspects; import com.ibm.aglet.Message; import no.ntnu.dias.agent.Agent; /**

Page 111: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 99 -

* @author Tore Steinmoen * @author Erlend Rønningen * * This aspect ensures that whenever handling a message it is * of correct type, meaning KQML (the format used in DIAS). * */ public aspect CheckMessageIsKQML { declare precedence : CheckMessageIsKQML, HandleMessaging; pointcut handleMessage(): execution(boolean handleMessage(Message)); /** * Makes sure when calling handleMessage(), the format of the message * is KQML. */ boolean around(Message message) : handleMessage() && args(message) { if (!message.sameKind("KQML")) return false; return proceed(message); } }

package no.ntnu.dias.aspects; import com.ibm.aglet.system.ContextEvent; import no.ntnu.dias.util.ServerApp; /** * @author Tore Steinmoen * @author Erlend Rønningen * * Logs public calls within ServerApp * @see no.ntnu.dias.util.ServerApp */ public aspect ContextEventLogger { pointcut contextEvents() : within(ServerApp) && execution(public * aglet*(..)); /** * Logs all public calls to methods within ServerApp (super * class for applications) * @param event the event which is argument to the method */ before(ContextEvent event): contextEvents() && args(event) { String methodName =

thisJoinPointStaticPart.getSignature().getName(); System.out.println(methodName + " : " + event.getAgletProxy() } }

Page 112: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 100 -

package no.ntnu.dias.aspects; import no.ntnu.dias.agent.*; import no.ntnu.dias.KQML.KQMLmessage; import com.ibm.aglet.Message; /** * @author Tore Steinmoen * @author Erlend Rønningen * * Prints exceptions */ public aspect ExceptionPrinter { // General exceptions private pointcut general() : handler(Exception+); // Not supported exceptions: private pointcut notSupported() : handler(NullPointerException) || handler(ArrayIndexOutOfBoundsException) || within(no.ntnu.dias.KQML...); private pointcut exceptions(Exception err) : ( general() && !notSupported() ) && args(err); /* * Prints a message whenever a method of the types defined in * exceptions is called. * Prints name of class and method where it happened + * the exception message. * The last part of the declaration is to make sure that we do not * get any hits in CORBA-generated classes. (from IDLs) */ before(Exception err): exceptions(err) &&

!within(no.ntnu.dias.amp.orb._MAF*) { String className =

thisJoinPointStaticPart.getSignature().getDeclaringType(). getName();

String methodName = thisEnclosingJoinPointStaticPart.getSignature().getName();

System.err.println("Error in " + className + "." + methodName + "(): " + err);

} }

package no.ntnu.dias.aspects; import no.ntnu.dias.agent.*;

Page 113: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 101 -

import com.ibm.aglet.Message; import no.ntnu.dias.KQML.KQMLmessage; import java.net.URL; import java.net.MalformedURLException; /** * @author Tore Steinmoen * * Handles messages arriving at an agent */ public privileged aspect HandleMessaging { pointcut targetClasses() :

within(no.ntnu.dias.agent.userAgent.UserAgent) || within(no.ntnu.dias.agent.systemAgent.SystemAgent);

pointcut handleMessage(Agent agent, Message message) : execution(boolean handleMessage(Message)) && target(agent) && args(message); /** * Takes arguments from the message. Based on those arguments * the right actions are chosen * @param agent the processing agent * @param message the message that have arrived */ boolean around(Agent agent, Message message) : handleMessage(agent, message) && targetClasses() { String className = thisJoinPointStaticPart.getSignature() .getDeclaringType().getName(); KQMLmessage kqmlMessage = (KQMLmessage) message.getArg(); String strOntology = kqmlMessage.getValue("ontology"); String performative = kqmlMessage.getValue("performative"); String receiver = kqmlMessage.getValue("receiver"); String subject = agent.getSubject(strOntology); boolean performativeTell = performative.equals("tell"); boolean ontologyTypeDIAS =

agent.getOntologyType(strOntology).equals("DIAS"); boolean wrongMessageType = !performativeTell ||

!ontologyTypeDIAS; boolean receiverEqualsMe = agent.agentID.equals(new

AgentID(receiver)); boolean isSystemAgent =

className.equals("no.ntnu.dias.agent.systemAgent. SystemAgent");

System.out.println(className + "::handleMessage() receiver: " +

receiver + ", subject: " + subject); if (receiver != null && !receiverEqualsMe && isSystemAgent) { return proceed(agent, message); } else if (wrongMessageType) { return proceed(agent, message); } else if (subject.equals("PRESENT_ON_DISCONNECTING_ADP")) { agent.sendAcknowledgement("YES", message); agent.presentOnDisconnectingADP();

Page 114: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 102 -

} else if (subject.equals("DISCONNECTED_FROM_DSP")) { agent.sendAcknowledgement("YES", message); agent.connectedToDSP = false; } else if (subject.equals("CONNECTED_TO_DSP")) { try { String strOriginAgentPlace =

agent.getURL(kqmlMessage); agent.urlOriginPlace = new

URL(strOriginAgentPlace); agent.sendAcknowledgement("YES", message); agent.connectedToDSP = true; } catch (MalformedURLException mue) { agent.sendAcknowledgement("NO", message); return false; } } else { return proceed(agent, message); } return true; } }

package no.ntnu.dias.aspects; import no.ntnu.dias.agent.*; import no.ntnu.dias.agent.systemAgent.SystemAgent; import no.ntnu.dias.amp.orb.DIAS; import no.ntnu.dias.KQML.KQMLmessage; import java.net.URL; /** * @author Tore Steinmoen * * Handles the strict messaging which is demanded in all agents but * system agents */ public privileged aspect StrictCommunication { pointcut agent_communicate() : call(KQMLmessage

Agent.communicate(KQMLmessage)); pointcut systemAgent_communicate() : call(KQMLmessage

SystemAgent.communicate(KQMLmessage)); pointcut notSystemAgents_communicate() : agent_communicate() &&

!systemAgent_communicate(); /** * Before calling communication on agents, check if it is allowed to * communicate This does not apply to systemagents. */ KQMLmessage around(Agent agent, KQMLmessage message) :

notSystemAgents_communicate() && target(agent) && args(message) {

String className =

Page 115: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 103 -

thisEnclosingJoinPointStaticPart.getSignature(). getDeclaringType().getName();

String methodName = thisEnclosingJoinPointStaticPart.getSignature(). getName();

correctMessageData(agent, message);

if (senderIdNotCorrect(agent, message) || isNotAllowedToCommunicate(agent, message)) {

return null; } return proceed(agent, message); } /** * Check if the message has all the data needed for communication, if * not correct them (inserting default values). * @param agent the current processing agent * @param message the message being communicated */ private void correctMessageData(Agent agent, KQMLmessage message) { AgentID agentID = agent.agentID; String sender = message.getValue("sender"); String receiver = message.getValue("receiver"); String ontology = message.getValue("ontology"); if (sender == null) { sender = agentID.toString(); } else { sender = (new AgentID(sender)).toString(); } message.addFieldValuePair("sender", sender); if (receiver == null) { receiver = new AgentID().toString(); } else { receiver = new AgentID(receiver).toString(); } message.addFieldValuePair("receiver", receiver); if (ontology == null) { ontology = "<ONTOLOGY

TYPE=\"GENERAL\"><SUBJECT></SUBJECT></ONTOLOGY>";

} else { // The ontology must be on the correct DTD format, // if not set to general if (agent.getXmlDocument(agent.diasDTD.getOntologyDTD() +

ontology, true) == null) { ontology = "<ONTOLOGY TYPE=\"GENERAL\"><SUBJECT>" + ontology + "</SUBJECT></ONTOLOGY>"; } } message.addFieldValuePair("ontology", ontology); } /** * Checks if the current agent's id is the same as is the message * @param agent current processing agent * @param message message being communicated

Page 116: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 104 -

* @return comparison between sender's id in message and agent's id */

private boolean senderIdNotCorrect(Agent agent, KQMLmessage message) {

String sender = message.getValue("sender"); return (!agent.agentID.toString().equals(sender)); } /** * This method does: * 1. Checks if the sender tries to communicate with * other agents outside ADP. * 2. If so it must be connected to a DSP or it must * be created in a DSP * * @param agent current processing agent * @param message message being communicated * @return check if sender's and receiver's URL is * correct and not the same. */ private boolean isNotAllowedToCommunicate(Agent agent, KQMLmessage

message) { boolean isNotAllowedToCommunicate = false; AgentID sender = new AgentID(message.getValue("sender")); AgentID receiver = new AgentID(message.getValue("receiver")); URL senderURL = sender.getAgentDSP(); URL receiverURL = receiver.getAgentDSP(); URL agentPlace = agent.getAgentPlace(); URL originPlace = agent.urlOriginPlace; boolean senderURLIsNull = (senderURL == null); boolean senderHaveDSP = agent.connectedToDSP; boolean receiverIsNull = (receiverURL == null); boolean OriginPlaceEqualsAgentPlace =

(agentPlace.equals(originPlace)); boolean receiverNotSameADP = true; if (!receiverIsNull) receiverNotSameADP = !receiverURL.equals(agent.urlOriginPlace); // Check if sender has no address and receiver is not connected // to the same DSP or have no address if (senderURLIsNull && receiverNotSameADP || receiverIsNull) isNotAllowedToCommunicate = true; // Check if sender is not connected to a DSP or created in a // DSP and if receiver is not connected to the same ADP if (!senderHaveDSP && OriginPlaceEqualsAgentPlace &&

receiverNotSameADP) isNotAllowedToCommunicate = true; // Try to connect to DSP boolean isConnected = agent.isConnected(); // Check if can not connected to a DSP and receiver is not // connected to same ADP or receiver has no address isNotAllowedToCommunicate = (!isConnected && receiverNotSameADP

|| receiverIsNull);

Page 117: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 105 -

return isNotAllowedToCommunicate; } }

package no.ntnu.dias.aspects; import no.ntnu.dias.agent.Agent; import no.ntnu.dias.adp.ADPInfo; import no.ntnu.dias.amp.AMPInfo; import no.ntnu.dias.agent.systemAgent.*; import no.ntnu.dias.diasDTD.DiasDTD; import org.xml.sax.*; import com.sun.xml.tree.*; import java.io.*; import java.net.URL; import java.net.MalformedURLException; /** * @author Tore Steinmoen * * Utilities for reading an XML document, using * a tree walker */ public aspect XmlDocumentUtils { interface WalkTree {} public DiasDTD WalkTree.diasDTD = new DiasDTD(); /** * XML-document from a string formed correctly as XML * @param tree contains the XML-tree * @param withDTD if the XML-tree is sent with DTD * @return the tree as XML-document */ public XmlDocument WalkTree.getXmlDocument(String tree, boolean

withDTD) { try { StringReader strRead = new StringReader(tree); InputSource in = new InputSource(strRead); return XmlDocument.createXmlDocument(in, withDTD); } catch (SAXException e) { } catch (IOException e) { } return null; } /** * Treewalker for a given XML-tree * @param tree contains the XML-tree * @param withDTD if the XML-tree is sent with DTD * @return walker for the XML-tree */ public TreeWalker WalkTree.getTreeWalker(String tree, boolean

withDTD) { XmlDocument xmlOntology = getXmlDocument(tree, withDTD); return getTreeWalker(xmlOntology); }

Page 118: Erlend Rønningen and Tore Steinmoen - Computer Science...originally is a part of a master thesis at NTNU. The system is implemented in Java, and we used AspectJ to restructure it.

- 106 -

/** * Treewalker for a given XML-tree * @param XML-tree * @return walker for the XML-tree */ public TreeWalker WalkTree.getTreeWalker(XmlDocument xmlOntology) { if (xmlOntology == null) return null; return (new TreeWalker(xmlOntology)); } public String WalkTree.getStringValueFromXML(TreeWalker walker,

String field) { try { Object xmlValue =

((ElementNode)walker.getNextElement(field)). getFirstChild();

return xmlValue.toString(); } catch (NullPointerException e) { } return null; } public int WalkTree.getIntValueFromXML(TreeWalker walker, String

field) { String valueString = getStringValueFromXML(walker, field); try { return Integer.parseInt(valueString); } catch (NumberFormatException e) { return 0; } } public URL WalkTree.getURLValueFromXML(TreeWalker walker, String

field) { String valueString = getStringValueFromXML(walker, field); try { return new URL(valueString); } catch (MalformedURLException e) { return null; } } declare parents: no.ntnu.dias.agent.* implements WalkTree; declare parents: ADPManagerAgent implements WalkTree; declare parents: AMPManagerAgent implements WalkTree; declare parents: FacilitatorAgent implements WalkTree; declare parents: ADPInfo implements WalkTree; declare parents: AMPInfo implements WalkTree; }