+ All Categories
Home > Documents > ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro...

ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro...

Date post: 26-Aug-2020
Category:
Upload: others
View: 0 times
Download: 0 times
Share this document with a friend
121
Universidade Federal de Pernambuco Centro de Inform´ atica os-gradua¸c˜ ao em Ciˆ encia da Computa¸ ao ANALISYS OF TECHNIQUES FOR IMPLEMENTING SOFTWARE PRODUCT LINES VARIABILITIES Pedro Osandy Alves Matos J´ unior DISSERTAC ¸ ˜ AO DE MESTRADO Recife 21 de agosto de 2008
Transcript
Page 1: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

Universidade Federal de PernambucoCentro de Informatica

Pos-graduacao em Ciencia da Computacao

ANALISYS OF TECHNIQUES FORIMPLEMENTING SOFTWARE PRODUCT

LINES VARIABILITIES

Pedro Osandy Alves Matos Junior

DISSERTACAO DE MESTRADO

Recife21 de agosto de 2008

Page 2: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram
Page 3: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

Universidade Federal de PernambucoCentro de Informatica

Pedro Osandy Alves Matos Junior

ANALISYS OF TECHNIQUES FOR IMPLEMENTING SOFTWAREPRODUCT LINES VARIABILITIES

Trabalho apresentado ao Programa de Pos-graduacao em

Ciencia da Computacao do Centro de Informatica da Uni-

versidade Federal de Pernambuco como requisito parcial

para obtencao do grau de Mestre em Ciencia da Com-

putacao.

Orientador: Prof. Dr. Paulo Henrique Monteiro Borba

Recife21 de agosto de 2008

Page 4: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram
Page 5: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

Aos meus pais.

Page 6: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram
Page 7: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

ACKNOWLEDGEMENTS

Agradeco, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci.Eles que sempre estiveram ao meu lado, oferecendo ajuda quando eu necessitava, meconsolando nos momentos tristes e tambem compartilhando meus momentos de alegria.Sem eles, nao teria conseguido chegar ate aqui.

Agradeco, em especial, ao meu orientador, Paulo Borba, por todas as dicas, co-mentarios e sugestoes que ele me deu durante esses anos. Por sempre ter se mostrandodisponıvel quando eu necessitei, nunca medindo esforcos para ver o sucesso dos seusalunos. E desnecessario comentar que, sem ele, esse trabalho nao existiria. Muitos deseus comentarios foram uteis para o desenvolvimento desse trabalho. Muitos outros forame serao uteis durante toda a minha vida.

Agradeco tambem a minha querida namorada, Camila, que esteve bastante presentenos ultimos meses em que estive concluindo esse trabalho. Sua presenca, carinho e com-preensao foram muito importantes para mim durante a conclusao dessa dissertacao.

Nao posso deixar de citar tambem todos os amigos e companheiros do SPG, pessoascom quem eu aprendi e me diverti bastante. Desses, faco uma mencao especial a Marcio(Marcinho SBT) e Ivan (Graaaande lıder), pois estiveram diretamente ligados a essetrabalho. Muito do que produzi durante esses anos foi resultado de reunioes e conversasinformais com essas pessoas maravilhosas. Menciono ainda Rafael Duarte que, apesar denao ser membro do SPG, tambem esteve bastante presente. Agradeco tambem a todasas pessoas ligadas ao projeto FLIP.

Tambem menciono aqui a grande contribuicao do CNPq e FINEP, por fomentaremesse projeto de pesquisa.

vii

Page 8: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram
Page 9: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

True glory consists in doing what deserves to be written; in writing what

deserves to be read; and in so living as to make the world happier for our

living in it.

—PLINY THE ELDER

Page 10: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram
Page 11: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

RESUMO

Linhas de Produtos de Software (LPS) sao conjuntos de sistemas de software que com-partilham uma base comum de funcionalidades e satisfazem a necessidades especıficas dedeterminados segmentos de mercado. LPS sao desenvolvidas a partir de uma arquiteturacomum e compartilham um conjunto de artefatos reusaveis (projetados para um domıniode aplicacao especıfico). Entre as atividades principais na construcao e manutencao deuma LPS esta a gerencia das variacoes nos diversos artefatos que a compoem. Em par-ticular, a escolha de tecnicas de programacao que possibilitem a introducao de variacoesem artefatos de implementacao e uma atividade que merece bastante atencao. A escolhade qual tecnica utilizar para lidar com determinados tipos de variacoes nos artefatos deimplementacao de uma LPS pode gerar impactos significativos tanto na qualidade dessesartefatos como na qualidade dos produtos finais gerados. Apesar da importancia dessaatividade, poucos estudos publicados mostram comparacoes entre as diversas tecnicasque permitem a implementacao de variacoes em software. A maioria dos trabalhos exis-tentes limita-se a avaliacoes qualitativas dessas tecnicas, nao analisando o impacto dessastecnicas nos atributos de qualidade de LPS existentes atraves de metricas de software.

O foco do presente trabalho e a comparacao entre algumas das tecnicas de imple-mentacao de variacoes usadas na industria de software. Para tal, primeiro apresentamosum catalogo de tipos de variacoes, onde variacoes sao classificadas de acordo com a suaestrutura e localizacao no codigo da aplicacao. As variacoes apresentadas no catalogoforam identificadas atraves de uma analise realizada em uma LPS do domınio de jogospara dispositivos moveis. Em seguida, apresentamos padroes de utilizacao de algumasdas principais tecnicas para lidar com cada tipo de variacao especıfico. Como parte dessetrabalho, analisamos o impacto da utilizacao de cada padrao atraves de dados qualitativose quantitativos. Analisamos ainda a composicao do uso desses padroes para implementarvariacoes em LPS e como um catalogo de tipos de variacoes e um conjunto de padroes deimplementacao de variacoes podem guiar a implementacao ou reestruturacao de variacoesem uma LPS.

Palavras-chave: Linhas de Produtos de Software, Programacao Orientada a Aspectos,Mixins

xi

Page 12: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram
Page 13: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

ABSTRACT

Software Product Lines (SPLs) are sets of software systems that share a common baseof features and satisfy the needs of specific market segments. SPLs are developed from acommon architecture and share a set of reusable artifacts (designed for a specific domain).Among the main activities in the life cycle of a SPL is the management of variations in allthe artifacts that belongs to it. Particularly, the choice of programming techniques thatenable variability in implementation artifacts is an activity that deserves much attention.The choice of which technique to use in order to deal with variations in the implementationartifacts of a SPL can result in significant impacts on the quality of these artifacts andalso in the resulting products. Although this is an important topic, few published studiesshow comparisons of the many techniques that enable variability in software. Most ofthese works are limited to qualitative evaluations of these techniques, not analyzing thereal impact of these techniques in the quality attributes of SPLs.

The focus of this thesis is the comparison of variability enabling techniques that areused by the software industry. To accomplish this task, we first present a catalog of vari-ation types, where variations are grouped according to their structure and location in thesource code. The variation types presented in the catalog were identified by an analysisin a SPL from the mobile games domain. After, we presented variability implementa-tion patterns, which use different techniques in order to deal with the identified variationtypes. As part of this work, we analyze the impact resulting from each pattern usingboth qualitative and quantitative evaluation. We also analyze the composition of thesepatterns in order to implement variabilities in SPLs and discuss how the presented cata-log of variation types and the set of patterns can guide the implementation of variationsin a SPL.

Keywords: Software Product Lines, Aspect-Oriented Programming, Mixins

xiii

Page 14: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram
Page 15: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

CONTENTS

Chapter 1—Introduction 1

1.1 Main Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21.2 Organization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3

Chapter 2—Background 5

2.1 Software Product Lines . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52.1.1 Commonalities in Software Product Lines . . . . . . . . . . . . . 82.1.2 Variabilities in Software Product Lines . . . . . . . . . . . . . . . 8

2.2 Techniques for Implementing Variabilities in Software Product Lines . . . 112.2.1 Conditional Compilation . . . . . . . . . . . . . . . . . . . . . . . 122.2.2 Inheritance and Mixins . . . . . . . . . . . . . . . . . . . . . . . . 142.2.3 Delegation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172.2.4 Aspect-Oriented Programming . . . . . . . . . . . . . . . . . . . . 172.2.5 Program Transformations . . . . . . . . . . . . . . . . . . . . . . 202.2.6 Configuration Files . . . . . . . . . . . . . . . . . . . . . . . . . . 21

2.3 Games for Mobile Devices Domain . . . . . . . . . . . . . . . . . . . . . 212.3.1 BestLap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22

2.4 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22

Chapter 3—Metrics and Criteria for Software Product Lines Evaluation 23

3.1 Complexity Metrics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233.2 Modularity Metrics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243.3 Separation of Concerns Metrics . . . . . . . . . . . . . . . . . . . . . . . 243.4 Efficiency Metric . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253.5 Adaptations of Metrics to Software Product Lines . . . . . . . . . . . . . 25

3.5.1 The Measurement Object . . . . . . . . . . . . . . . . . . . . . . 253.5.2 Classes Dependent on Inter-Type Declarations . . . . . . . . . . . 273.5.3 Separation of Concerns vs Separation of Variants . . . . . . . . . 28

3.6 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29

Chapter 4—Variation Types and Implementation Patterns 31

4.1 Variation Type 1: Variation in Class Attribute . . . . . . . . . . . . . . . 324.1.1 Patterns for Variation in Class Attribute . . . . . . . . . . . . . . 334.1.2 Evaluation of Patterns for Variation in Class Attribute . . . . . . 40

xv

Page 16: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

xvi CONTENTS

4.1.2.1 Evaluation of Patterns for Alternative Initialization Values 404.1.2.2 Evaluation of Patterns for Optional Attributes . . . . . . 45

4.2 Variation Type 2: Variation in Class Hierarchy . . . . . . . . . . . . . . . 484.2.1 Patterns for Variation in Class Hierarchy . . . . . . . . . . . . . . 494.2.2 Evaluation of Patterns for Variation in Class Hierarchy . . . . . . 51

4.3 Variation Type 3: Variation in the Whole Body of a Method . . . . . . . 544.3.1 Patterns for Variation in the Whole Body of a Method . . . . . . 564.3.2 Evaluation of Patterns for Variation in the Whole Body of a Method 62

4.4 Variation Type 4: Variation in the Beginning or End of Method Body . . 654.4.1 Patterns for Variation in the Beginning or End of Method Body . 664.4.2 Evaluation of Patterns for Variation in the Beginning or End of

Method Body . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 694.5 Variation Type 5: Variation in a Structure Around Method Body . . . . 71

4.5.1 Patterns for Variation in a Structure Around Method Body . . . . 714.5.2 Evaluation of Patterns for Variation in a Structure Around Method

Body . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 754.6 Final Considerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77

4.6.1 Beyond the Catalog of Variation Types . . . . . . . . . . . . . . . 774.6.2 Crosscutting Variabilities vs Non-crosscutting Variabilities . . . . 784.6.3 Quantification in Aspect-Oriented Programming . . . . . . . . . . 78

4.7 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78

Chapter 5—Evaluation 79

5.1 Applicability of Patterns . . . . . . . . . . . . . . . . . . . . . . . . . . . 86

Chapter 6—Concluding Remarks 89

6.1 Contributions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 906.2 Related Work . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 906.3 Open Issues and Future Work . . . . . . . . . . . . . . . . . . . . . . . . 91

Page 17: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

LIST OF FIGURES

2.1 The key activities for software product lines development [21]. . . . . . . 62.2 Costs for developing n kinds of systems as single systems compared to

product line engineering [54]. . . . . . . . . . . . . . . . . . . . . . . . . . 72.3 The Variability Funnel with early and delayed variability [35]. . . . . . . 92.4 Example of a feature diagram. . . . . . . . . . . . . . . . . . . . . . . . . 112.5 Inheritance technique used to define specializations. . . . . . . . . . . . . 152.6 Feature composition implemented with single inheritance. . . . . . . . . . 162.7 Feature composition implemented with multiple inheritance or mixins. . . 172.8 Screen captures from BestLap mobile game. . . . . . . . . . . . . . . . . 22

5.1 Screen captures from Arena optional feature. . . . . . . . . . . . . . . . . 80

xvii

Page 18: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram
Page 19: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

LIST OF TABLES

4.1 LOC metric for patterns used to implement alternative initialization valuesfor class attributes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42

4.2 VS metric and other metrics for comparing the impact of patterns usedto implement alternative initialization values for attributes in MainCanvasclass. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42

4.3 Metric for showing the impact of use of Pattern 2 on Screen128X128 aspectand Pattern 3 on Screen128X128 properties file. . . . . . . . . . . . . . 42

4.4 Concern diffusion and variant diffusion metrics for the patterns used toimplement alternative initialization values for class attributes. . . . . . . 43

4.5 BS metric for the patterns used to implement alternative initializationvalues for class attributes. . . . . . . . . . . . . . . . . . . . . . . . . . . 44

4.6 LOC metric for patterns used to implement optional class attributes. . . 464.7 VS metric and other metrics for comparing the impact of use patterns used

to implement optional attributes in Resources class. . . . . . . . . . . . . 464.8 Metric for showing the impact of use of Pattern 2 on DebugAspect and

Pattern 4 on ResourcesDebug class. . . . . . . . . . . . . . . . . . . . . . 464.9 BS metric for the patterns used to implement optional attributes. . . . . 474.10 VS metric for the patterns used to implement Variation in Class Hierarchy. 514.11 Complexity metrics for the patterns used to implement Variation in Class

Hierarchy. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 524.12 CBC metric for the implementations of Pattern 5 and Pattern 6. . . . . . 524.13 Concern diffusion and variant diffusion metrics for the implementations of

Pattern 5 and Pattern 6. . . . . . . . . . . . . . . . . . . . . . . . . . . . 534.14 Concern tangling and variant tangling metrics for the implementations of

Pattern 5 and Pattern 6. . . . . . . . . . . . . . . . . . . . . . . . . . . . 534.15 BS metric for the implementations of Pattern 5 and Pattern 6. . . . . . . 544.16 LOC metric for patterns used to implement Variation in the Whole Body

of a Method. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 624.17 VS metric and metrics for the patterns used to implement Variation in the

Whole Body of a Method on SoundEffects class. . . . . . . . . . . . . . . 624.18 Metrics for Pattern 8 and Pattern 9. . . . . . . . . . . . . . . . . . . . . 634.19 Metrics for Pattern 10. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 634.20 Metrics for Pattern 11. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 634.21 BS metric for the patterns used to implement Variation in the Whole Body

of a Method (a). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 644.22 BS metric for the patterns used to implement Variation in the Whole Body

of a Method (b). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65

xix

Page 20: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

xx LIST OF TABLES

4.23 Metrics for patterns used to implement Variation in the Beginning or Endof Method Body. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69

4.24 LOC metric for patterns used to implement Variation in the Beginning orEnd of Method Body. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69

4.25 Other complexity metrics and CBC metric for patterns used to implementVariation in the Beginning or End of Method Body. . . . . . . . . . . . . 69

4.26 BS metric for for the patterns used to implement Variation in the Begin-ning or End of Method Body. . . . . . . . . . . . . . . . . . . . . . . . . 70

4.27 VS metric for patterns used to implement Variation in a Structure AroundMethod Body. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75

4.28 LOC metric for patterns used to implement Variation in a Structure AroundMethod Body. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75

4.29 Complexity metrics for comparing the impact of use patterns used to im-plement Variation in a Structure Around Method Body in artifacts specificof Pattern 16 and Pattern 17. . . . . . . . . . . . . . . . . . . . . . . . . 76

4.30 BS metric for for the patterns used to implement Variation in a StructureAround Method Body. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76

5.1 Metrics for BestLap SPL where Arena feature is implemented using con-ditional compilation technique. . . . . . . . . . . . . . . . . . . . . . . . 80

5.2 Metrics for BestLap SPL where Arena feature is implemented using Java’sinheritance mechanism. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82

5.3 Metrics for BestLap SPL where Arena feature is implemented using Cae-sarJ’s mixin-based inheritance mechanism. . . . . . . . . . . . . . . . . . 83

5.4 Metrics for BestLap SPL where Arena feature is implemented using AOPtechnique. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84

5.5 NOEDA and NOEDO metrics for BestLap SPL where Arena feature isimplemented using AOP technique. . . . . . . . . . . . . . . . . . . . . . 84

5.6 Complexity and scattering metrics for Arena feature for the four versionsof our case study. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85

5.7 Bytecode Size metric values for Arena feature experiments. . . . . . . . . 865.8 Bytecode Size metric values for Arena feature experiments . . . . . . . . 87

Page 21: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

LISTINGS

2.1 Conditional compilation example. . . . . . . . . . . . . . . . . . . . . . . 13

2.2 AOP Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18

4.1 Example of Variation in Class Attribute (a). . . . . . . . . . . . . . . . . 33

4.2 Example of Variation in Class Attribute (b). . . . . . . . . . . . . . . . . 33

4.3 Example of Variation in Class Attribute (c). . . . . . . . . . . . . . . . . 34

4.4 Example of Attribute Defined by Conditional Compilation pattern to han-dle attributes with alternative initialization values. . . . . . . . . . . . . 35

4.5 Example of Attribute Defined by Conditional Compilation pattern to han-dle optional attributes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35

4.6 Example of Attribute Defined by Inter-Type Declaration pattern to handleattributes with alternative initialization values. . . . . . . . . . . . . . . 36

4.7 Example of Attribute Defined by Inter-Type Declaration pattern to handleoptional attributes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37

4.8 Example of Attribute Initial Value Defined by Configuration File patternto handle attributes with alternative initialization values. . . . . . . . . . 38

4.9 Example of Attribute Defined by Subclass pattern to handle optional at-tributes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39

4.10 Example of Variation in Class Hierarchy (a). . . . . . . . . . . . . . . . . 48

4.11 Example of Variation in Class Hierarchy (b). . . . . . . . . . . . . . . . 48

4.12 Example of Variation in Class Hierarchy (c). . . . . . . . . . . . . . . . . 49

4.13 Example of Variation in Class Hierarchy (d). . . . . . . . . . . . . . . . 49

4.14 Example of Class Hierarchy Defined by Conditional Compilation patternto handle variability in the hierarchy structure of MainCanvas class. . . . 50

4.15 Example of Class Hierarchy Defined by Inter-Type Declaration pattern tohandle variability in the hierarchy structure of MainCanvas class . . . . . 51

4.16 Example of Variation in the Whole Body of a Method (a). . . . . . . . . 55

4.17 Example of Variation in the Whole Body of a Method (b). . . . . . . . . 55

4.18 Example of Variation in the Whole Body of a Method (c). . . . . . . . . 55

4.19 Example of Whole Body of a Method Defined by Conditional Compilationpattern to handle alternative behaviors for playSound method in Sound-Effects class. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56

4.20 Example of Whole Body of a Method Defined by Inter-type Declaration pat-tern to handle alternative behaviors for playSound method in SoundEffectsclass. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57

4.21 Example of Whole Body of a Method Defined by Around Advice pattern tohandle alternative behaviors for playSound method in SoundEffects class. 59

xxi

Page 22: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

xxii LISTINGS

4.22 Example of Whole Body of a Method Defined by Strategy pattern to handlealternative behaviors for playSound method in SoundEffects class. . . . . 60

4.23 Example of Whole Body of a Method Defined by Method Override patternto handle alternative behaviors for playSound method in SoundEffects class. 61

4.24 Example of Variation in the Beginning or End of Method Body. . . . . . 664.25 Example of Variation in the Beginning or End of Method Body Defined by

Conditional Compilation . . . . . . . . . . . . . . . . . . . . . . . . . . . 674.26 Example of Variation in the Beginning or End of Method Body Defined by

After/Before Advice . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 674.27 Example of Variation in the Beginning or End of Method Body Defined by

Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 684.28 Example of Variation in a Structure Around Method Body. . . . . . . . . 714.29 Example of Structure Around Method Body Defined by Conditional Com-

pilation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 724.30 Example of Structure Around Method Body Defined by Around Advice. . . 734.31 Example of Structure Around Method Body Defined by Inheritance. . . . 74

Page 23: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

CHAPTER 1

INTRODUCTION

Software Product Lines (SPLs) [21] are families of software products that share a baseset of common features. They are developed from a common architecture, and share aportfolio of reusable assets. The adoption of SPLs is a solution to software developmententerprises that develop software systems that have to adapt to different constraints orto satisfy the requirements of clients with distinct or conflicting expectations. They canchoose to develop a single managed SPL, and instantiate software systems according totheir needs, instead of developing many independently managed software systems whichdo not reuse efforts among their development activities, or do it in an ad-hoc way.

The adoption of development strategies based on SPLs can bring advantages like shorttime-to-market, reduced development costs, better quality in the resulting products andimproved client satisfaction [21]. Despite all these advantages, the development of SPLsalso implies additional investments and complexity, as most of the activities are concernedin creating assets that are reusable.

The existing literature has already addressed how to manage the development of SPLs,or to deal with genericity in high-level assets, like domain models and architectures. How-ever, little attention has been given on how to actually deal with the genericity that SPLsrequire at the source code level [12]. Some programming techniques are known for en-abling the implementation of variabilities, however, programmers have little informationto decide which technique should be chosen in different situations. We argue that thechoice of the correct technique can lead to significant impacts on the quality attributesof SPLs.

Few works have been published on this topic and most of them focus on discussingqualitative attributes of each technique [12, 53, 59, 24]. Also, a very small number ofthem conducts experiments and use metrics to quantitatively assess the impact of eachtechnique. More research in this topic is indeed necessary. In fact, that is the focus ofthis thesis.

One assumption of our work is that there is no variability implementation techniquethat always outperforms the others. Indeed, this assumption has been evidenced by otherresearchers [12, 53, 59, 24]. Some techniques are not able to implement some types ofvariabilities in a scalable way. Also, different domains imply different expectations forthe development techniques. A software development company that creates informationsystems, for example, may give priority to well modularized and easy to understandcomponents, whereas a company that develops embedded systems, usually priorizes lowconsumption of resources in the resulting products.

In order to compare techniques, we have first defined a set of comparison criteria:complexity of implementation artifacts, modularity, separation of concerns and efficiencyin size of the resulting applications. Although we may not have considered every possible

1

Page 24: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

2 INTRODUCTION

criteria, we think that this is a good set because these criteria are relevant in mostapplication domains. We also have considered some metrics to evaluate these criteria.While most of the metrics are well established for single systems engineering, we alsohave defined new metrics for our purposes and defined some guidelines to use of the wellestablished metrics in the context of SPLs. In addition to that, we have developed asimple tool to help the calculation of metrics following our guidelines.

To compare the techniques, we have first proposed variability implementation patterns.These patterns define how a technique can be applied to address a specific type of variationin the source code. We have grouped these patterns into a catalog of variation types. Forevery type of variation from the catalog, a portfolio of patterns is offered to deal with it.The criteria for grouping patterns into variation types were the location in the source codewhere the variation appears and the varying source code structure. With this decision,we intend to help the implementation of variabilities in existing source code, using theextractive and reactive SPL adoption strategies, as we explain in the next chapters.

We have conducted rigorous analyzes for every variation type of the catalog. A singlevariation point in the source code of an existing SPL (initially implemented with theconditional compilation technique) is implemented with each pattern associated withthat variation type. After, we compared the impact of the use of each pattern in respectto the criteria we have defined. This gives to the programmer the necessary informationto choose a pattern to apply, given the current context and priorities for each criteria.Also, our patterns are not just a recommendation of a technique to be used. They are adescription of how a specific variation type can be handled by a given technique. Thus,it becomes easier for the programmer to apply the pattern. In the future, these patternscould be included in a SPL development tool to provide semi-automation to the variabilityimplementation activity, as discussed latter.

As we consider separation of concerns as a criteria to chose techniques, we also haveperformed a case study where a whole crosscutting variability from a industrial mo-bile game is implemented using our approach. We then, compare results obtained byeach technique. We have identified the necessity to perform this case study becausethe full benefits of using a technique that supports modular implementation of crosscut-ting concerns, like aspect-oriented programming, are only seen when a whole concern isimplemented with this technique. We discuss this issue latter in this thesis.

The case study was also useful to evaluate our hypothesis that our catalog of variationtypes,and portfolio of variability implementation patterns, can be used as a guideline toimplement variabilities in SPLs.

1.1 MAIN OBJECTIVES

The main goals of the thesis are:

� The definition of criteria, metrics and guidelines to evaluate implementations ofSPLs;

� A catalog of variation types, in conjunction with a portfolio of variability imple-mentation patterns (using different techniques) to address each variation type;

Page 25: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

1.2 ORGANIZATION 3

� Evaluation of the performance of each pattern according to different criteria, inorder to help software developers to decide which pattern is best suited for hisspecial case;

� Evaluate the performance of some techniques to implement crosscutting variabili-ties.

The problem we try to solve is the fact that software developers often do not havethe necessary information to chose a variability enabling technique, when implementinga SPL. The consequences of this problem can be negative impacts on quality attributesof both implementation and resulting products of this SPL.

The concrete benefits of our solution are: an increased confidence of the softwaredeveloper when choosing which technique to use in order to implement variabilities in aSPL; a reduction in the chance that a software developer chooses a technique that havea negative impact on a critical quality factor of the SPL being implemented.

1.2 ORGANIZATION

The remainder of the thesis is organized as follows:

� Chapter 2 presents some background information that is relevant to the under-standing of this thesis. Concepts of Software Product Lines are explained, as wellas some variability enabling techniques are presented. Finally, it discuss particular-ities and variabilities found in domain of mobile games, and also presents BestLap,an industrial mobile game used as case study in this thesis;

� Chapter 3 discuss the criteria used to compare variability implementation tech-niques, in conjunction with the metrics used to assess these criteria. In this chapter,it is discussed how traditional software metrics can be applied in a context of SPLsand some new metrics are presented to this purpose;

� Chapter 4 presents the catalog of variation types that we have identified. For everyvariation type, a set of specific implementation patterns are proposed. We evaluatethe use of these patterns to handle a single occurrence of the variation type in thesource code of BestLap using our set of metrics and criteria. We also make someconsiderations about the use of the variation types catalog and implementationpatterns;

� Chapter 5 evaluates the use of the variation types catalog and variability imple-mentation patterns to implement a crosscutting variability of BestLap;

� Chapter 6 concludes this thesis, discussing the summary of results and presentingsome related works. It also discuss some open issues of this thesis and points somefuture works.

Page 26: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram
Page 27: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

CHAPTER 2

BACKGROUND

In this chapter, we present some background information that is relevant to the under-standing of this thesis. This chapter is organized as follows: in Section 2.1, we introduceconcepts related to Software Product Lines and variabilities; Section 2.2 complements theprevious section, by discussing some of the most relevant techniques to handle variabili-ties at the implementation level; finally, in Section 2.3, we introduce the domain of gamesfor mobile devices and discuss what kinds of variabilities can be find in this domain.

2.1 SOFTWARE PRODUCT LINES

The Software Engineering Institute (SEI) defines Software Product Lines (SPLs) as a setof software-intensive systems that share a common, managed set of features satisfying thespecific needs of a particular market segment or mission and that are developed from acommon set of core assets in a prescribed way [36].

The concept of software families were first introduced by Dijkstra and Parnas. Di-jkstra [26] proposed a model of family-based development where differences in designdecisions distinguished family members. Parnas [52] characterized families as groups ofitems that are strongly related by their commonalities, where commonalities are moreimportant than the variations among family members. The concept of software reuse isalso not new. It has been proposed some decades ago [49] as a possible solution to theexisting software crisis.

The SPL approach differs from common software reuse by ensuring that each reusableasset is developed within a software family scope and has a clear purpose in this scope.Moreover it enforces management commitment with the development process. Theseare critical success factors to any reuse program. Since reusable assets are harder todevelop and maintain, the decision to develop a component in a reusable fashion shouldbe careful analyzed by cost vs benefits models. That it, a reusable asset should onlybe developed when a cost vs benefit analysis shows that it is better than developingindividual components for each specific application. The SPL approach also enforces thatany necessary customizations to reusable assets, in order to build specific products (namedinstances), are well documented. This constraint enforces that a product instantiation isstraightforward process. Thus, most of the work in a SPL is concentrated on developingand documenting reusable assets, while the instantiation of a product is an easier task.

It is also important to say that reusable assets does not only means implementationartifacts, but every common or customizable artifact that is shared among the SPLinstances. Reusable assets can be artifacts that are part of the development process (forexample, requirements and design documents) or part of the final product (for example,binary files, images, sound files, documentation). We define core asset as being anyartifact that is used to instantiate more than one product in a SPL. Thus, core assets

5

Page 28: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

6 BACKGROUND

Figure 2.1 The key activities for software product lines development [21].

refers to the set of artifacts (be it part of the development process or part of a finalproduct) that are shared by at least two instance of a SPL.

The key activities in SPLs development are shown in Figure 2.1. Each of the threecircles represent an activity. The Core Asset Development activity is motivated by thedomain engineering, whose focus is to analyse the SPL domain and search for reuseopportunities within its scope. The core assets provide support for the Product Devel-opment activity, which is part of the application engineering. The focus of the ProductDevelopment activity is to combine and configure core assets and, if necessary, to developapplication specific components in order to instantiate a new product. Both activitiesare supported and coordinated by the Management activity.

Pohl et al. list some benefits from adopting a SPL approach [54]:

� Reduction of Development Costs. When core assets are reused to instantiateseveral products, the overall cost to create all the system is drastically reduced.The cost to create new products on a mature SPL should be very low. Despitethat, higher upfront investments are required in order to develop reusable assets.Thus, the initial costs to develop a SPL are higher than the initial cost to developa single product, however the total accumulated cost is lower as the SPL evolves,when comparing to the development of several independent systems. Figure 2.2shows a comparison of the accumulated costs to develop a SPL with n instancesor n independent software products. The break-even point in the figure is thepoint where the costs are the same for developing the systems separately as fordeveloping them by a SPL approach. As shown in Figure 2.2, some empiricalstudies revealed that the upfront investments to initiated a SPL usually Pay-offaround three systems [21]. This three systems number is not a rule, though. Manyfactors contribute to when the break-even point will be reached, like applicationdomain, organization experience, and SPL adoption strategy [48, 42];

� Enhancement of Quality. As the number of instances increase, the reusableassets get more tested. In a mature SPL, the reusable assets already had their

Page 29: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

2.1 SOFTWARE PRODUCT LINES 7

Figure 2.2 Costs for developing n kinds of systems as single systems compared to product lineengineering [54].

quality assured in many products, thus, new products using these assets tends tobe more reliable than products developed from scratch;

� Reduction of Time-to-Market. As the effort required to instantiate a newproduct in a SPL is much lower than the effort required to develop a independentsystem, the time to release new products can be significantly reduced. Becauseof the upfront investments required to develop a SPL, the time-to-market of thefirst products should be higher than the regular time-to-market to develop a singlesystem. The time-to-market tends to be reduced for new products, as the SPLevolves.

SPLs can be developed using different adoption strategies. In [48, 42], three adoptionstrategies for SPLs are proposed: proactive, reactive, and extractive. In the proactiveapproach, the organization analyzes, designs, and implements a fresh SPL to support thefull scope of products needed on the foreseeable horizon. In the reactive approach, the or-ganization incrementally grows an existing SPL when the demand arises for new productsor new requirements on existing products. In the extractive approach, the organizationextracts existing products into a single SPL. For small or medium-sized organizations,or domains where time-to-market is critical, reactive and extractive approaches are pre-ferred over since the proactive approach demands high upfront investments and createsmore risks.

Page 30: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

8 BACKGROUND

2.1.1 Commonalities in Software Product Lines

Commonalities constitutes the basis of SPLs. They can be defined as the set of decisionsthat are common to all products in a software family. They are the motivating factorsto develop a SPL. The more commonalities a set of software products have, the more aenterprise will benefit from developing them in a SPL approach. In fact, it only makessense to develop a SPL when the members of the software family have a substantial setof commonalities among them. This is coherent with the Parnas’ concept of softwarefamiles [52]: ¨We consider a set of programs to constitute a family, whenever it is worth-while to study programs from the set by first studying the common properties of the setand then determining the special properties of the individual family members¨.

Coplien[23] also presents commonalities as abstractions. If we examine a family ofrelated software systems, we can ignore some details and reason about the whole familythrough abstractions. These abstractions are the commonalities. Coplien also distinguishdeductive commonality from inductive commonality. The former relates to experience,whereas the latter relates to learning. We discover commonalities in an inductive waywhen we are familiar with the set of system to be developed. Thus, we can proposeabstraction based on our past experience. When we face a new situation, no learnedmodel applies well. We try to find abstractions by seeking for repetition. In the absenceof analogy and experience, deductive reasoning is applied.

2.1.2 Variabilities in Software Product Lines

Variability is another key concept for the understanding of SPLs. Variation managementis a key discriminator between conventional software engineering and SPL engineering.Before proceeding with this section, it is important to distinguish variability in timefrom variability in space. Variability in time refers to the evolution of a software systemover the time. It is addressed in conventional software engineering through configurationmanagement activities and is not the focus of this thesis. On the other hand, variabilityin space refers to the differences among the instances of a SPL at a fixed point in time.Conventional software engineering deals with variability in time only, whereas SPL en-gineering deals with variability in both time and space [43]. On the remaining of thisthesis, when we use the term variability alone, we are referring to variability in space.

Variability in SPLs allows developers to delay some design decisions. We refer to thesedelayed decisions as variation points. Acording to [54], a variation point is a representa-tion of a variability subject within domain artefacts enriched by contextual information.For each individual instance of a SPL, we bind specific decisions to the variation points.These specific decisions are called variants. Whenever a decision is made, we say thatthe variability is bound.

Figure 2.3 illustrates how the available space of design decisions differs from commonsystem engineering to SPL engineering. The funel on the left side represents the evolutionof the domain of design decisions on common systems engineering, whereas the funnel onthe right side represents the same information for SPL engineering. In both cases, theinitial possibilities of final systems is very large at the requirements specification phase.In single systems engineering, the number of possible systems is reduced in a fast way,

Page 31: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

2.1 SOFTWARE PRODUCT LINES 9

Figure 2.3 The Variability Funnel with early and delayed variability [35].

through the development lifecycle, culminating to a single product at the end. On theother hand, in SPLs development the number of possible systems is smoothly reduced asthe development evolves, leading to a set o possible instances at the end. That is, SPLsengineering allows developers to late bind variabilities.

Variabilities can be classified based on their binding time, i.e the time in which thespecific variant is decided. The binding time for a variability can be:

� Compile-Time: variability is resolved when the source code for the SPL is beingcompiled. We also consider variabilities that are bound before the actual compila-tion, like the ones implemented by code preprocessor tools, as part of this category;

� Load-Time: variability is resolved during module or library linking, just beforethe program is run;

� Run-time: variability is bounded when the program is running. The contextinformation to decide which variant to be selected can be provided by input fromthe user, or inferred from the running environment (adaptative systems).

Variability only makes sense when it is related to a commonality base [23]. We cannot talk about variability when we do not have a commonality as referential. Thus, wecan classify variability by the way they relate to the commonality base:

� Positive variability: leaves the commonality model untouched and add an extrabehavior;

� Negative variability: removes existing behavior from the commonality base,breaking some existing assumptions on the commonality model.

Page 32: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

10 BACKGROUND

Positive variability is preferred against negative variability, since it preserves the com-monality assumptions and thus, makes the overall SPL easier to understand and maintain.For example, one way to implement negative variabilities is to use inheritance with cance-lation [57]. This technique violates the Liskov substitutability principle [46], which statesthat an instance of a class should always be substitutable by an instance of any of itssubclasses without breaking programs that was written making assumptions about theparent class.

Based on the argument that negative variabilities break the common structure, whichis the skeleton of the component, Patzke and Muthig [53] suggest that they should beavoided and turned into positive ones. Coplien [23], however, states that there are somesituations where negative variabilities should be considered; for example, when almostall instances of a SPL behaves in the same way and one particular instance excepts fromthe rule. Moreover, he states that negative variabilities should be considered in a contextwhere the variation becomes larger than the commonality. We agree with this positionbut with observation that the system designer should carefully think about the use ofnegative variabilities, since they can be harmful to the overall understanding of the SPLstructure. The system design should always consider the possibility to transform negativevariabilities into positive ones. Furthermore, in cases where the number of variations ismuch higher than the number of commonalities, maybe it is the time for the systemdesigner to do a cost vs benefit analysis in order to decide if it is really worth to take theSPL engineering approach.

Variabilities can also be classified by their relationships with other variabilities. Acommon way to show the variabilities of a product family is to use feature diagrams,which were first introduced in the Feature-Oriented Domain Analysis(FODA) methodol-ogy [39]. Feature diagrams present all the features of a product family in a hierarchicaltree, representing the relationships among these features. Features shown in a featurediagram can be one of the following four types:

� Mandatory Features: represent the commonality of a product family. Themandatory features must be included in every product of the family;

� Optional Features: as the name says, this feature is a variability, which can bepresent or not in a specific product of the family;

� Mutual-Exclusive Alternative Features (XOR-Features): features of thistype belong to a group of features from which no more than one must be selected;

� OR-Features: like XOR-features, this kind of feature also belongs to a group offeatures, however, the selection of more than one feature of this group is allowed.

An example of a feature diagram is shown in Figure 2.4. This feature diagram rep-resents a family of cars. In a feature diagram, features are represented by rectanglescontaining their names and the relationships among them are represented by lines andarcs. A mandatory feature is identified by a black circle above the feature’s rectangle,whereas a optional feature is identified by an empty circle. In the example, every car

Page 33: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

2.2 TECHNIQUES FOR IMPLEMENTING VARIABILITIES IN SOFTWARE PRODUCT LINES 11

Figure 2.4 Example of a feature diagram.

must support some kind of fuel and must be painted in some color, however, not everycar is obligated to have an airbag. OR-features and XOR-features are identified by anarc which groups them together. An black arc represents a set of OR-features, while anempty arc represents a set of XOR-features. In the example shown in Figure 2.4, carsare allowed to support, as fuel, either only gasoline, only ethanol, or both. A car can,however, be painted in only one color: blue, black or red. The feature diagram from Fig-ure 2.4 was created in Captain Feature [4], an multi-platform tool for modeling featuresand drawing feature diagrams.

Although feature diagrams are useful to provide an graphical visualization for thefeatures (commonalities and variabilities) of a SPL and their relationships, the graphicalelements from the diagram are not able to specify every possible relationships constraints.When more complex constraints are necessary, they are usually specified as a complementto the diagram in natural language, or in a constraints specification language which allowsautomated checking.

2.2 TECHNIQUES FOR IMPLEMENTING VARIABILITIES IN SOFTWARE PROD-UCT LINES

In the previous section, we introduced the concept of SPLs and how the variabilitiesinteract among them in a SPL context. In this section, we focus on presenting some of themost relevant technologies to deal with variabilities at the implementation artifacts of aSPL. Components in a SPL context are usually more complex than components developedfor a single software product. They must support a higher level of generalization than itis used in common systems engineering. These components should also be easily adaptedto fit in the context of different software products. The objective of this section is not toprovided a detailed description of each technique, but to briefly introduce their conceptsand to discuss how they support the implementation of variabilities. These techniquesare presented in the next subsections.

Page 34: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

12 BACKGROUND

2.2.1 Conditional Compilation

Conditional Compilation, or code preprocessing is one the most elementar, yet mostpowerful, techniques to enable variabilities in implementation artifacts. When usingthis technique, the blocks of source code related to a variability are enclosed by specialpreprocessor directives. The source code artifacts which contain these directives must bepreprocessed before they can be compiled.

For the purposes of this work, we have used Antenna [2], a set of Ant [3] tasks suitablefor developing J2ME applications. Antenna provides, among other features, a source codepreprocessor. Antenna preprocessor provides a set of directives which support variabilityin source code. The most important are [2]:

� #ifdef [identifier] The identifier represents a variable, which can be related to avariability. This directive checks whether or not the variable is defined. If true (thevariable is defined), the code that follows is processed. Nested blocks are processedas well. If false (the variable is not defined), the code that follows is commentedand nested blocks are not evaluated. The directive must be closed with #endif;

� #ifndef [identifier] Similar to the previous directive, but the condition is evalu-ated to true if the identifier is not defined;

� #elifdef [identifier] Works as a standard else if statement for ifdef/ifndef blocks.Can only be used inside blocks started by ifdef/ifndef;

� #elifndef [identifier] Similar to the previous directive, but the condition is eval-uated to true if the identifier is not defined;

� #if [expression] Works similar to the ifdef directive, however evaluates an expres-sion instead of a single identifier. It also must be closed with endif;

� #elif [expression] Works as a standard else if statement and can complementonly in blocks started by an if statement;

� #else Works as a standard else statement only preprocesses the code that followswhen none of the previous conditions in the defining block were true. Complementsinside any block started with the if/ifdef/ifndef directive;

� #endif Must be used to close any block started with if/ifdef/ifndef.

Listing 2.1 shows an example where an optional feature is implemented with Antenna’ssource code preprocessor. The class in the example represents a bank account. Theblocks of source code which are enclosed by preprocessor directives implement an featurewhich notifies clients (by e-mail or SMS) every time an debit or credit operation isperformed is their bank accounts. The NOTIFY CLIENTS symbol is associated withthis optional feature. The ifdef tags in lines 15, 24 and 29 (in conjunction with their endifenclosing directives) ensure that the blocks of code which belong to this feature will onlybe considered during the compilation step if the NOTIFY CLIENTS symbol is defined

Page 35: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

2.2 TECHNIQUES FOR IMPLEMENTING VARIABILITIES IN SOFTWARE PRODUCT LINES 13

during the code preprocessing step. Notice that preprocessor directives dot not dependon any structure of the Java language, and thus be used to implement variabilities at anylocation in the source code.

1 public class Account {2 private long number ;3 private double balance ;4 private Cl i en t c l i e n t ;56 public Account ( long number , C l i en t c l i e n t ) {7 this . number = number ;8 this . ba lance = 0 ;9 this . c l i e n t = c l i e n t ;

10 }1112 public void c r e d i t (double value ) {13 balance = balance + value ;14 //#i f d e f NOTIFY CLIENTS15 this . n o t i f y C l i e n t ( ” Credit Operation : ”+ value ) ;16 //#e n d i f17 }1819 public void deb i t (double value ) {20 i f ( ba lance >= value ) {21 balance = balance − value ;22 }23 //#i f d e f NOTIFY CLIENTS24 this . n o t i f y C l i e n t ( ” Debit Operation : ”+ value ) ;25 //#e n d i f26 }2728 //#i f d e f NOTIFY CLIENTS29 private void n o t i f y C l i e n t ( S t r ing message ) {30 [ . . . ]31 }32 //#e n d i f33 }

Listing 2.1 Conditional compilation example.

As the conditional compilation technique is based on tagging the implementationartifacts with meta-information, which is independent from the actual compilation of theartifact, it shows itself as a very powerful tool for implementing variabilities in a SPL.Conditional compilation can be used to implement complex variabilities, and yet resultin zero overhead in the resulting applications.

This technique, however, has its drawbacks. The first is that, as the preprocessormust take place just before the compiler, the variabilities implemented with this tech-nique must be decided at compile-time. Another drawback is that this technique provides

Page 36: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

14 BACKGROUND

no modularity for the variability implementation. The implementation of the variabilityis not confined in a set of modules dedicated to this special purpose, but rather spreadthroughout other implementation artifacts, which imposes difficulties to the understand-ing of the implementation of the variability and maintenance activities related to thisvariability. Moreover, the overall understanding of the source code of the SPL can becompromised, specially when many variabilities are implemented with this technique andwhen many cases of interaction among these variabilities occur - which result in nestedifdefs in the implementation artifacts.

In spite of these drawbacks, this technique is heavily used in operating systems andembedded systems domains, as application of these domais have to deal with strongresources restrictions and the conditional compilation technique usually results in nomemory and processing overheads to handle the variabilities.

2.2.2 Inheritance and Mixins

Inheritance is a mechanism provided by languages of the object-oriented paradigm. Thismechanism allows specialized classes (subclasses) to refine the structure and behaviorof more general classes (parent classes). These refinements can define new attributesand operations and also redefine the behavior of some operations that already existed inthe parent class (method override). Programmers of the object-oriented paradigm oftensee inheritance as mechanism to provide code reuse. If two or more classes have somecommon behavior or structure, this commonality can be placed in an abstraction (parentclass) which theses classes can refine.

Positive variabilities fits well in this context. They can be implemented as refinementsof classes, adding the necessary behavior and structure to deal with each variability.As instances of a subclass can be used in contexts where instances of a parent class isexpected, the rest of the program do not need to be modified. Also, in most object-oriented languages, a method call can be late bound to an object at run-time. Thismechanism is known as dynamic binding or virtual methods, and allows variabilities tobe decided at run time. The decision of the variability is done by instantiating the correctclass. Some object-oriented design patterns like Factory Method and Abstract Factorycan be used to handle this variability in class instantiation [33].

Negative variability can not be addressed well with inheritance technique. The re-striction that instances of subclasses should be able to substitute instances of their parentclasses in any context, imposes that structure and behavior can be added, but not re-moved when refining classes. This restriction is often referred to as Liskov substitutionprinciple [46]. This is a high desirable property of object-oriented programs, even if itis not enforced by the programming language. Consider a scenario where a programmercreates a class A, which represents an ordered list of elements. Other programmers coulduse instances of class A with the assumption that it preserves the order of the elementswhich are inserted. Now, consider that the same programmer creates a class B, whichrefines A (B is a subclass of A) and do not preserve the ordered list constraint. Notethat as B is a subclass of A, instances of B can be used in contexts where instances of Aare expected. If an instance of B is used in a context where instances of A are expected

Page 37: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

2.2 TECHNIQUES FOR IMPLEMENTING VARIABILITIES IN SOFTWARE PRODUCT LINES 15

Figure 2.5 Inheritance technique used to define specializations.

and the context depend on the assumption that this instance would preserve the order ofthe elements, the program would be incorrect, because this assumption is broken in classB. Negative variability can be implement using inheritance technique by overriding somemethods in the subclasses. By using method override, it is possible to cancel the behaviorof some method, by just leaving the new definition of the method with an empty body,or by implementing some new functionality which breaks some pre or post conditions ofthe overridden method.

Inheritance can be used to implement both optional and alternative features. Themost simple form of inheritance, single inheritance, allows each subclass to have a max-imum of one parent class, whereas the latter can be refined by an arbitrary number ofsubclasses. Thus, one (optional) refinement can be defined for a class, as well as many(alternative) refinements. The fact that single inheritance allows only one parent classper subclass, however, has an impact when it is necessary to compose two or more refine-ments.

Consider the Car product line example we have discussed in Section 2.1.2. Supposethat a car is specified in a class named Car which abstracts what type of fuel is usedby the car’s engine. Cars which support Gasoline or Ethanol as fuel can be definedas specializations (subclasses) of the Car class, GasolineCar and EthanolCar classes 1.A UML (Unified Modeling Language) class diagram [32] for this example is shown inFigure 2.5.

This single example can be easily accomplished using a single inheritance mechanism.Now, suppose that we want to specify cars which support both gasoline and ethanol asfuel. To implement this new specialization of car with single inheritance, a developerwould define a new subclass, GasolineAndEthanol class which refines Car class directly.This schema is shown in Figure 2.6. The main problem of this approach is that, althoughGasolineAndEthanol class is a semantic composition of GasolineCar and EthanolCar

1We have omitted other features to simplify the discussion.

Page 38: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

16 BACKGROUND

Figure 2.6 Feature composition implemented with single inheritance.

classes, it is impossible to define a class which inherits the structure and behavior fromboth GasolineCar and EthanolCar classes at the same time. The consequence of thislimitation is source code replication. Part of the refinements defined in GasolineCarand EthanolCar classes would have to be repeated in GasolineAndEthanol class. Inthis example, we have considered only a single composition of two features, in orderto show the problem. This scenario can get even worse if we consider compositionsof multiple optional features. The single inheritance mechanism does not scale well tofeature compositions at classes level, so another solution is required.

On possible solution is to use multiple inheritance. Multiple inheritance allows sub-classes to extend directly from more than one parent class and thus, allow a feature com-position to be define as refinement of two or more classes (a subclass with two or moreparent classes). This approach avoids source code replication, since structure and behav-ior is inherited in the composition class from the two or more parent classes. Figure 2.7shows how GasolineAndEthanol class can be defined as a composition of GasolineCarand EthanolCar classes using multiple inheritance.

Multiple inheritance solves the feature composition problem but creates new problems,such as ambiguities that arise when a clash occurs in the names of attributes or opera-tions inherited from different parent classes2 and the lack of a standard semantics [18].One alternative to multiple inheritance is to use mixins based inheritance. Mixins allowsfeatures composition at the class level in a scalable way and avoid some of the prob-lems of multiple inheritance [18]. Mixins often are implemented using a technique calledlinearization which is much simpler than multiple inheritance.

For the purposes of this work, have we used the mixins mechanism of CaesarJ [14]programming language. A deeper discussing about the semantics of mixins and how theyavoid the problems of multiple inheritance are out of the scope of this work. In thenext section, we discuss delegation, a technique which is often used in association withinheritance.

2Often referred to as the diamond problem.

Page 39: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

2.2 TECHNIQUES FOR IMPLEMENTING VARIABILITIES IN SOFTWARE PRODUCT LINES 17

Figure 2.7 Feature composition implemented with multiple inheritance or mixins.

2.2.3 Delegation

In this technique, the developer removes variabilities from the classes which implement thecommonality and place them in specific classes. The classes from which the variabilitieswere removed hold references to objects which are able to deal with specific variations.When a code related to some variation (optional or alternative) needs to be executed,the class calls the associated operation from the variability object, that is, it delegatesthe variability to another object.

In object-oriented programs, delegation is often used in association with inheritance.The classes which implement the commonality base hold referentes to objects whichimplement optional or alternative variabilities. Often, an abstract data type is usedto declare these references and the correct objects are instantiated at run-time. Oneclassic example of delegation and inheritance techniques being used together to implementvariabilities is the Strategy design pattern [33].

2.2.4 Aspect-Oriented Programming

Aspect-oriented programming (AOP) was proposed as a solution to the problem ofimplementing crosscutting concerns [40]. Crosscutting concerns are functional or non-functional characteristics of a program whose implementations are naturally spread through-out the program’s source code. They can not be implemented using traditional object-oriented techniques in a modular way. Classical examples of crosscutting concerns are:

Page 40: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

18 BACKGROUND

logging, persistence control, concurrency control and transaction control.Two problems arise when crosscutting concerns are implemented using only object-

oriented techniques: scattering and tangling. We say that the implementation of a concernin scattered when it is present in many modules of a system, that is, many modules con-tribute to the implementation of this concern. In addition to that, the implementationof may concerns can be tangled in a module, that is, source code lines related to differentconcerns are interleaved in the same module. Tangling and scattering difficult the un-derstanding of programs and make maintenance activities harder. It also becomes verydifficult to enable specific concerns at compile-type or even at run-time, as required in aSPL infrastructure.

Aspect-oriented languages support two concepts: quantification and obliviousness [30].Crosscutting concerns are defined apart from the other concerns (base code) in specificmodules (often called aspects). These modules can define new a behavior which affectsthe base code in many different points (quantification). Also, the base code is oftenoblivious to the existence of these modules (aspects).

AspectJ [44] is an aspect-oriented extension to Java. Programming with AspectJinvolves both aspects and classes to separate concerns. Concepts that are well definedwith object-oriented constructs are implemented in classes. Crosscutting concerns areusually separated using units called aspects, which are integrated with the classes througha process called weaving. Thus, an AspectJ application is composed of both classes andaspects. Therefore, each AspectJ aspect defines a functionality that affects differentparts of the system. Aspects may define pointcut designators (or pointcuts for short),advices, and intertype declarations. Pointcut match join points, which are a set of pointsduring program execution flow, where we may want to execute a piece of code. Codeto be executed at join points matched by pointcuts is declared as an advice. Inter-type declarations are structures that allow introducing fields and methods into a class,changing the hierarchy of a type (making a class extend another class or implement aninterface), and turning checked exceptions into unchecked exceptions.

AspectJ language enables the implementation of crosscutting variabilities in a SPL. Italso makes the variability decision mechanism easier. Once the aspects are created, theycan be added or not during or after the compilation of the program, using the AspectJweaver. Standard AspectJ supports weaving only before the program is loaded into thevirtual machine, and once an aspect is weaved into the a program, this process can notbe undo. This is a restriction of the current AspectJ weaver, though. It is not limitationof the AOP paradigm.

Remind the example introduced in Section 2.2.1, when we discussed conditional com-pilation. The implementation of the client notification concern were tangled with otherconcerns in Account class. With AOP, it is possible to define this concern in a singleaspect. Listing 2.2 shows the implementation of the referred example using AspectJ.Aspect NotifyClients implement the discussed concern by defining two advices and oneinter-type declaration.

1 public class Account {2 private long number ;3 private double balance ;

Page 41: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

2.2 TECHNIQUES FOR IMPLEMENTING VARIABILITIES IN SOFTWARE PRODUCT LINES 19

4 private Cl i en t c l i e n t ;56 public Account ( long number , C l i en t c l i e n t ) {7 this . number = number ;8 this . ba lance = 0 ;9 this . c l i e n t = c l i e n t ;

10 }1112 public void c r e d i t (double value ) {13 balance = balance + value ;14 }1516 public void deb i t (double value ) {17 i f ( ba lance >= value ) {18 balance = balance − value ;19 }20 }21 }2223 aspect N o t i f y C l i e n t s {24 a f t e r ( Account account , double value ) :25 execut ion (void Account . c r e d i t (double ) )26 && this ( account ) && args ( va lue ) {27 account . n o t i f y C l i e n t ( ” Credit Operation : ”+ value ) ;28 }2930 a f t e r ( Account account , double value ) :31 execut ion (void Account . deb i t (double ) )32 && this ( account ) && args ( va lue ) {33 account . n o t i f y C l i e n t ( ” Debit Operation : ”+ value ) ;34 }3536 private void Account . n o t i f y C l i e n t ( S t r ing message ) {37 [ . . . ]38 }39 }

Listing 2.2 AOP Example

See that the source code of Account class is oblivious to the existence of NotifyClientsaspect. It should be noticed, however, that simple refactorings in Account could breakNotifyClients aspect. In a ideal scenario, one programmer should be able to developAccount class, at the same time that another programmer develops NotifyClients aspect,without communicating. In that way, the programmer responsible for Account classwould be oblivious to the existence of any aspect affecting this class. And both artifacts,Account and NotifyClients, could evolve independently. This scenario, however, is notpossible because AspectJ’s constructs dependent on syntactic elements of the the base

Page 42: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

20 BACKGROUND

code. So, although there is no syntactic reference in a classes to aspects, these twoelements can be semantically coupled [50]. One solution to this problem is to defineinterfaces between aspects and classes, as proposed by some researchers [58, 41, 34].

Quantification is supported by AspectJ’s pointcut model. It is possible to defineadvices which affects many joinpoints in a program. Although this is a clear benefit ofAspectJ, it can also cause some problems. If quantification is not used carefully it can leadto advices that affects more joinpoints than it is desirable, resulting in incorrect programs.Some approaches were proposed to tame the power of AspectJ’s pointcuts [8, 16].

Other extensions to the Java language provide aspect orientation. ABC [15] is an openan highly customizable AspectJ compiler which allows developer to easily extend the baseAspectJ language by creating new joinpoints, adding new constructs to the language oroptimizing the weaving process. In [47], an extension to ABC is proposed to optimizethe weaving process, reducing the overhead on the size of the resulting application andoffering opportunities for other obfuscation tools to make further optimizations. In thiswork, we have used this extension, since we examine the mobile games domain, in whichthe size of the deployed application is a very important issue.

CaesarJ [1] is another AOP extension to Java. It supports AspectJ’s pointcuts andadvices constructs but do not support inter-type declarations. It also support someadvanced features, like mixins, virtual inner classes and wrappers [14].

2.2.5 Program Transformations

Program transformation systems can also be used to implement variabilities in a SPL.They are able to describe complex variability patterns, even crosscutting ones. They canalso be used to implement variabilities in different levels of granularity, ranging from asingle line of source code to the package or component level.

Program transformation systems can be language dependent or independent. In ad-dition to the fact that they can be used in conjunction with any programming language,language-independent program transformation systems can be used to implement vari-abilities of any granularity, since they are not restricted by a set o language constructs.One example of a language independent transformation system is XVCL (XML-BasedVariant Configuration Language) [37]. On the other hand, language-specific programtransformation systems can explore a set of language constructs in order to specify trans-formations in a more clean and safe way. One example of a language-specific programtransformation system is the Java Transformation System (JaTS) [51], which is designfor the Java programming language.

JaTS transformations are written in a language that extends Java with JaTS con-structs. The goal of the constructions is to allow type (class or interface) matching andthe specification of new types that are to be generated. A JaTS transformation consists oftwo parts: a left-hand side (matching template) and a right-hand side (replacement tem-plate). Both sides consist of one or more type declarations written in JaTS. The left-handside of a transformation is matched with the source Java type being transformed, whichimplies that both must have similar syntactic structures. The right-hand side defines thetype that will be produced by the transformation.

Page 43: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

2.3 GAMES FOR MOBILE DEVICES DOMAIN 21

The program transformations technique can be used to implement both alternativeand optional features, but it only support compile-type as the binding time, since trans-formations must be applied to the source code.

2.2.6 Configuration Files

The use of configuration files is another technique which enables variabilities in a SPL.Configuration files can be used to store alternative values for attributes used by theprogram. These attributes can represent variability on some data parameters used duringthe program execution, like integer or string attribute, or even variability in the controlflow of the program, by using boolean attributes. A configuration file can be read at loadtime or at run time.

In this work, we use Java properties files as a representation of this technique [6].However, more powerful mechanisms for configuration files exist. JPEL [56], for exam-ple, is a framework which allows the values of attributes to change at run-time, when aproperties file is changed. It also allows to specify attributes, in configuration files, as for-mulas, instead of constant values. The analysis of the use of more powerful configurationfiles mechanisms in SPLs is regarded as a future work.

2.3 GAMES FOR MOBILE DEVICES DOMAIN

In order to compare variability enabling techniques in existing SPLs, we chose the gamesfor mobile devices domain. Games for mobile devices are indeed simpler than gamesfor other platform due to restrictions of memory and processor power of current mobiledevices. On the other hand, developers of applications from this domain have to dealwith adhere to strong portability requirements, sice a single game usually have to bedeployed to a dozen or more platforms [11, 20]. J2ME [5], as one of the programmingenvironments more frequently used for implementing mobile games, reduce the problemby providing the portability characteristic of the Java language.

There are some portability issues that are not solved by the J2ME environment. Someprevious researches have identified some of them [9, 19]:

� Different features of the devices regarding user interface, such as screen size, numberof colors, pixel size, sounds, and keyboard layout;

� Different execution memory availability and maximum application size;

� Proprietary Application Programming Interface (API) and optional packages;

� Different profiles (MIDP 1.0 and MIDP 2.0);

� Different implementations of a same profile in J2ME;

� Device-specific bugs;

� Internationalization.

Page 44: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

22 BACKGROUND

Figure 2.8 Screen captures from BestLap mobile game.

Despite all efforts of device manufacturers to make achieve software compatibility,mobile game developers still have to create many different versions of the same game.Thus, this domain can benefit from a SPL architecture.

2.3.1 BestLap

BestLap is a mobile game developed by Meantime Mobile Creations and currently offeredby service carriers in South America, Europe, and Asia. The game is deployed to a totalnumber of 65 devices, which are grouped into 17 families. Each family represents a setof compatible devices running the same game code and thus, an instance of this SPL.

It is a casual race game where the player tries to achieve the best time in one lap andqualify for the pole position. In order to do that, the player has to succeed at severaltime trial mini games. The better the performance at the games, the better the time forthe lap. Player score is dependent on lap time and bonuses acquired during the games.The best scores are saved in high scores tables. Optionally, user scores can be posted ina server and ranked against each other.

BestLap SPL is implemented in J2ME platform using the conditional compilationtechnique. In this work, we have explored the use of other techniques to implementevariabilities originally implemented with conditional compilation. The original BestLapimplementation is composed by 15 classes and 10,345 lines of source code.

We have used BestLap for the experiments described in this thesis. BestLap wasalready used as case study in some of our previous works [38, 25]. Figure 2.8 shows somescreen captures from the game.

2.4 SUMMARY

In this chapter we have discussed some topics that are relevant to the understandingof this thesis. In the next chapter, we present some metrics and evaluation criteria tocompare implementations of SPLs.

Page 45: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

CHAPTER 3

METRICS AND CRITERIA FOR SOFTWAREPRODUCT LINES EVALUATION

In this section, we discuss the set of metrics we have chosen to quantitatively evaluateeach implementation technique. Most of these metrics are used in [55] and [29]1. Inaddition to the metrics that are already used in the academia, we have also defined fournew metrics: NOEDA, NOEDO, CVDC, and NCVC, which we discuss in Section 3.5.2and in Section 3.5.3. We also propose an approach to apply the existing metrics, whichwere originally proposed for single systems, in the context of a SPL.

The metrics are grouped according to four criteria. Metrics to evaluate the complexityof the implementation artifacts that constitute a SPL are presented in Section 3.1. InSection 3.2, we present the metrics used to assess modularity in a SPL context. Metricsrelated to separation of concerns are shown in Section 3.3. And, finally, in Section 3.4we discussed the Bytecode Size metric, used to measure the efficiency in the generatedapplication bytecode.

In Section 3.5, we discuss an approach to apply metrics in a SPL context. We alsointroduce some new metrics that are relevant to the evaluation of SPL implementations.

3.1 COMPLEXITY METRICS

These metrics can be used to assess the complexity of source code artifacts. A SPL withmany components, having many lines of source code is harder to maintain than a simplerone.

Vocabulary Size (VS): Counts the number of implementation assets that are partof the SPL. Implementation assets include source files (both classes and aspects) andconfiguration files.

Lines of Code (LOC): Counts the number of lines of code for each implementationasset. Comments and blank lines are ignored.

Number of Attributes (NOA): Counts the number of attributes of each implementa-tion asset. For aspects we count both aspect’s fields and inter-type fields defined insidethe aspect. For configuration files, we count each entry as an attribute.

Number of Operations (NOO): Similar to the NOA metric, this metric counts thenumber of operations (methods and advices) for each implementation asset.

1These works also use some metrics that were defined previously elsewhere.

23

Page 46: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

24 METRICS AND CRITERIA FOR SOFTWARE PRODUCT LINES EVALUATION

Weighted Operations per Component (WOC): Meausures the complexity of acomponent, in terms of its operations (methods or advices). Consider a component Cwith operations O1, ..., On. Let c1, ..., cn be the complexity of the operations. Then: WOC= c1 + ....+ cn. We consider the number of formal parameters of a operation as the factorof complexity, as operations with many formal parameters are more likely to be complexthan operations which require less parameters. In this way, we define the complexityof operation Ok, ck as following: ck = αk + 1, where αk denotes the number of formalparameters of Ok.

3.2 MODULARITY METRICS

The metrics described in this section are related to the modular understanding and in-dependence between modules in a SPL.

Coupling between Components (CBC): Counts, for each component (implemen-tation asset), the number of other components to which it is coupled. We consider thatcomponent A is coupled to component B, whenever the declaration of A references B insome way. For classes, a reference can be a local variable or attribute declaration, dec-laration in the formal parameters list of a method, the return type of a method, throwsdeclaration and object creation. To deal with aspects, this metrics encompass other di-mensions of coupling as describe in [55]. More specifically, this metrics considers accessesto aspect methods and attributes defined by inter-type declarations and the relationshipsbetween aspects and classes or other aspects defined in pointcuts and advices. Moreover,we extended this metric to consider also configuration files, as they are important im-plementation artifacts in a SPL context. A class or aspect is coupled to a configurationfile whenever it access any property define in this file. If a component A is coupled to acomponent B in an arbitrary number of forms, CBC counts only once.

Lack of Cohesion in Operations (LCOO): Lack of Cohesion in Operations (LCOO).This metric measures the lack of cohesion of a component (class or aspect). If a compo-nent Ck has n operations (methods and advices) O1, ..., On then Ij is the set of instancevariables of Ck used by operation Oj. Let Pk = {{Oi, Oj} : Oi ∈ Ck∧Oj ∈ Ck∧Ii∩Ii = ∅}and Qk = {{Oi, Oj} : Oi ∈ Ck ∧ Oj ∈ Ck ∧ Ii ∩ Ii 6= ∅}, for a component Ck. That is,Pk is the set of unordered operation pairs of Ck which have a null intersection betweentheir instance variables sets and Qk is the set of unordered operation pairs of Ck whichhave a non-empty intersection between their instance variables sets. Then LCOOk =|Pk| − |Qk|, if |Pk| > |Qk|, or LCOOk = 0 otherwise; where |Pk| and |Qk| represents thecardinality of Pk and Qk, for a component Ck, respectively.

3.3 SEPARATION OF CONCERNS METRICS

The metrics described in this section are used to measure the level of separation of con-cerns among the components. These metrics can reveal problems like scattering and

Page 47: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

3.4 EFFICIENCY METRIC 25

tangling.

Concern Diffusion over Components (CDC): Counts the number of componentsthat contribute to the implementation of a concern. A high value for CDC metric indi-cates that a concern implementation might be scattered. Guidelines for discovering whichcomponents contribute to a concern implementation can be found at [27].

Degree of Scattering (DoS): Degree of scattering [27] is a measure of the variance ofthe concentration of a concern over all components. The metric is normalized between 1(completely delocalized, uniformly distributed) and 0 (completely localized) inclusive.

Number of Concerns per Component (NCC): Counts the number of different con-cerns that a component implements. A high value for NCC metric is a signal thatimplementations of different concerns are tangled in a component.

3.4 EFFICIENCY METRIC

We measure the efficiency of each implementation using the Bytecode Size metric. Thismetric is very relevant in the context of games for mobile devices, because of the memoryrestrictions that most of these devices have.

Bytecode Size (BS): This metrics refers to the size of the application package file(jar file) for each instance of a SPL. Jar files contains not only compiled classes andwoven aspects, but also any resources that may be necessary to run the application, likeimages, sound files, and configuration files. We calculate the jar file size after applyingany bytecode optimization or obfuscator tools, that is, we measure only the size of thefiles that would be distributed to an end user.

3.5 ADAPTATIONS OF METRICS TO SOFTWARE PRODUCT LINES

The metrics we discussed so far have been used by the software industry to assess im-portant information of software products. Traditional metrics and approaches to applymetrics, however, can fail to reveal important information when applied in a SPL context.In this section, we discuss some questions related to the use of metrics in a SPL context.We also propose some new metrics in order to deal with the mentioned problems.

3.5.1 The Measurement Object

The first question that arises is whether we should apply a metric to the SPL as awhole, or apply it individually for each instance. To evaluate implementation techniques,we decided to apply source code metrics to the SPL as whole. The reason for thischoice was that we wanted to evaluate how the adoption of a technique over anotherwould affect maintenance and evolution activities on a SPL over its lifecycle. Thus, weconsider all the artifacts of the SPL, when calculating source code metrics, whether theyare used to build all products or only in a subset of the SPL instances. Moreover, we

Page 48: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

26 METRICS AND CRITERIA FOR SOFTWARE PRODUCT LINES EVALUATION

do not preprocess source code files containing conditional compilation directives beforecalculating the metrics. We also count each preprocessor directive as a valid line for theLOC metric, as they contain relevant and necessary information to the source code of theSPL.

In some situations it may be useful to calculate source code metrics for individualSPL instances. One example is when we want to measure the complexity of a specificSPL instance, that is, how hard is to understand the behavior of that particular instanceby looking to the source code. In this case, only the part of the source code that is usedto build the instance would be considered. It should be noted that this approach is onlyvalid if the variations are implemented in separated modules, with well defined interfacesbetween them. It does not make sense to calculate source code metrics for individualinstances, when the SPL uses a technique that does not provide modular implementationof variabilities, such as conditional compilation. Furthermore, even if we can understandthe code of a particular instance in a modular way, in order to execute maintenance andevolution activities on a SPL, we still need to understand the SPL’s architecture andhave general knowledge of the SPL as a whole. Thus, for the purposes of this work, wedecided to calculate source code metrics for the SPL as a whole, as stated before.

In contrast to source code metrics, BS metric is calculated for each SPL instance. Thereason to this is that we need to instantiate the SPL before calculating the size of theresulting jar file. On the other hand, we are not interested on the impact of choosing oneimplementation technique over another on the bytecode size of a specific instance. Weare interested in measuring how the implementation technique choice impacts the SPLas a whole. Thus, although we calculate BS metric for each individual instance, we areinterested on the average impact of one implementation technique on the bytecode sizeof all SPL’s instance.

Calculating metrics for a whole SPL can be a hard task because there are alternativecode artifacts or code blocks that are mutually exclusive. It does not make sense to createa product that uses all these alternative artifacts or blocks. Thus, it is very common thatthe whole code of a SPL does not even compile. In fact, it was not made to be compiledas a whole. In this scenario a problem arises: traditional software metrics tools willnot be able to calculate the desired metrics. A specialized suit of metrics tools can bedeveloped to address this issue, but this requires an initial investment. On the other hand,calculating metrics for each individual instance of a SPL can be a very time consumingtask, as SPLs can have a very high number of instances.

To help the calculation of metrics in our experiments, we developed a simple parserand analysis tool using SableCC [7], a Java compiler compiler. This allowed us to calcu-late complex metrics like CBC and LCOO that would be very time consuming, or evenimpractical, to calculate manually. We also developed some scripts to deal with simplemetrics, like LOC and BS. Calculating these metrics without some kind of automationwould also be a very error-prone task. Although the programs we had developed helpedus a lot in doing metrics calculation, they are far from being a professional or completemetrics tool suit for SPLs. For the purposes of this work, we focused on developing simpleutility programs that could help us on our specific tasks. Indeed, more research on met-rics definition and metric tools for SPLs is needed. We regard this as a very important

Page 49: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

3.5 ADAPTATIONS OF METRICS TO SOFTWARE PRODUCT LINES 27

future work.

3.5.2 Classes Dependent on Inter-Type Declarations

Another concern that arises when applying metrics on SPLs is related to AspectJ’s inter-type declarations. As we discussed in Section 2.2.4, one way to modularize variations ina SPL is to extract a method or attribute definition to an aspect. Thus, the declarationof such method or attribute is omitted in the body of the class and is defined in anaspect, which introduces the method or attribute into the class using an inter-type decla-ration construct. One important question is whether we should consider these introducedmembers as part of the class or as part of the aspect for metrics calculation purposes.

A method or attribute that is declared as an inter-type declaration is counted bymetrics like NOO and NOA as members of the aspect, as they are defined inside the scopeof the aspect’s body. In fact, this measurement strategy makes sense for a single productdevelopment context. Inter-type declarations can be seen as part of the implementation ofa crosscutting concern, which is encapsulated in an aspect. These members are accessedby other members of the same aspect (methods or advices) and the base code is usuallyoblivious to their existence. Thus, they do not contribute to the complexity of the classto which they are being introduced.

In a SPL context, the situation can be different, as mentioned before. The membersintroduced by inter-type declarations, often are semantic parts of the class to which theyare being introduced2. The reason to put their declaration inside the body of an aspectis to separate the part of the code that represents the commonality from the part thatimplements a variation. By moving an attribute’s definition to an aspect, we can vary itsinitialization value, in the same way that we can move the definition of a method to anaspect and vary its body, while the base code remains agnostic to this variability. In thisparticular case, it is easy to notice that although the member is defined inside the body ofan aspect, they are, in fact, semantic members of the class. They are, or can be, accessedfrom other locations of the source code as they were defined inside the body of the class.They can even be accessed inside the class body itself. In these cases, the developer ofthe base code is not agnostic in relation to the existence of these members. If we do notconsider them during the metrics calculation, we are hiding important information aboutthe base code’s complexity. We defined a new couple of metrics to deal with this issue.

Number of Externally Defined Attributes (NOEDA): Counts the number of at-tributes that are semantic members of a particular implementation asset, but are definedoutside its scope.

Number of Externally Defined Attributes (NOEDO): Counts the number of op-erations that are semantic members of a particular implementation asset, but are definedoutside its scope.

2This type situation is not specific to SPLs, but they are more common in this context than in thedevelopment of single systems.

Page 50: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

28 METRICS AND CRITERIA FOR SOFTWARE PRODUCT LINES EVALUATION

These metrics should not be used alone, but as a complement to NOA and NOO metrics,in a SPL context. To decide if a member (method or attribute) that is introduced toa class is a semantic part of this class, we search for references to this members in theSPL source code. If we find references outside the module that defines the member, thenother parts of the code are considering this member as part of the class, and thus weconsider it as a semantic part of the class. According to this definition, an inter-typedeclaration with the private access modifier will never be considered semantic part ofany class. As AspectJ’s semantics states that access modifier of inter-type declarationrefers to the aspect in which they are defined, not to the entity to which they are beingintroduced, a private inter-type declaration can not be accessed outside the scope of anaspect.

3.5.3 Separation of Concerns vs Separation of Variants

Another set of metrics that deserve attention are the separation of concerns metrics. Theywere first proposed to identify situations where crosscutting concerns are not implementedin a modular way. By analyzing metrics like CDC and NCC, it is possible to identifyproblems like tangling and scattering in a program’s source code.

When developing SPLs, we often have to deal with concerns that have a set of al-ternative implementations, that is, they are the projection of a feature with alternativevariants. Developers of a SPL can benefit from implementing each variant in a distinctmodule, since it becomes possible to reason about the each variant in a modular way.Developing each variant in a separated module also helps the instantiation process. Toinstante a new product, the developer only have to chose, among the available modules,the one which represents the desired variant and use this module during the productbuild process. A developer needs to be aware that variant modularity is an importantquality factor in SPLs and should be analyzed in conjunction with concern modularity.For analyzing variant modularity, we have proposed two new metrics:

Concern Variant Diffusion over Components (CVDC): Counts the number ofcomponents that are assigned to the implementation of a variant of a given concern. Theguidelines for discovering which components are assigned to variants are the same fordiscovering concern assignments [27].

Number of Concern Variant per Component (NCVC): Counts the number ofdifferent variants for a given concern that are assigned to a component. Let X be analternative concern from a SPL which has n variants (n > 0). Then, NCV Cx for acomponent C is the number of variants of concern X that are assigned to component C.

The analysis of these metrics is important because sometimes metrics used to assessseparation of concerns conflict with metrics used to assess separation of variants. Con-sider a situation where a concern X has n variants: v1, v2, ..., vn. One possibility is toimplement each variant of concern X in a distinct module. If we compare this implemen-tation with another that places all the variants of concern X in a single module, M, we

Page 51: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

3.6 SUMMARY 29

would come to the conclusion that the implementation of concern X is more scattered inthe first situation. However, if we calculated NCVC metric for the module M from thesecond situation we would discover a high tangling level at the variant level. In a SPLcontext, it is desirable to have separation of concerns and modularity at the variant level,even it implies in a higher scattering for a concern that encompass many variants.

3.6 SUMMARY

In this chapter, we have presented the criteria we are going to use in the remaining ofthis thesis to compare implementations of SPLs. We also have presented some metricsthat can be used to assess these criteria, and how these metrics can be applied for aSPL, instead for a single software system. In the following chapter, we present a catalogof variation types and a set of variability implementation patterns to deal with eachvariability type. The patterns are compared using the criteria and metrics we discussedin this chapter.

Page 52: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram
Page 53: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

CHAPTER 4

VARIATION TYPES AND IMPLEMENTATIONPATTERNS

In order to evaluate different variability implementation techniques, we proposed a modelthat consists of a catalog of types of variations and, for each type of variation, a set ofimplementation patterns that can be used to handle variations of that type.

We decided to group variabilities by the location in the source code where they appear,for example, in the declaration of an attribute or a method; and what part of the structureis varying; for example the initialization value of an attribute or the body of a method.The motivation for this choice was the focus on the development of SPLs using extractiveand reactive adoption approaches1. In both approaches, a software developer modifiesexisting implementation artifacts in order to implement variabilities at specific points.Our objective is to create a catalog of variation types that helps software developersduring this activity.

The focus on source code can also help the development of variation extraction thatcan make suggestions to the software developer about the techniques that can be usedto implement variabilities at selected blocks of code. Such tools may also automaticallyapply transformations in the source code in order to enable variability [17].

The variation types we present in this chapter were identified in the BestLap SPL.Originally, all the variations in the source code of BestLap were implemented using con-ditional compilation. To evaluate our set of variability implementation patterns, we havechosen examples of variation points in the source code of BestLap that matched each vari-ation type of our catalog. Then, we implemented each variation point with every patternthat is able to handle the variation types, resulting in different versions of BestLap (ineach one, the chosen variation point is implemented using a different pattern). After, wecompared these versions to evaluate the impact of each pattern in the quality attributesof BestLap.

In this chapter, we evaluate only the impact of single applications of each patternin a specific variation point. We compare the performance of all the patterns that areused to implement the same variation type. The objective of this evaluation is to helpsoftware developers to chose the best pattern for each variation point in the source codewhen implementing a SPL using the extractive or reactive approach. Notice that, in thischapter, we do not study the evolution of the SPL as it is done in [28]. Each analysis(which focus in one variation point) is independent.

The evaluation of single applications of patterns has some limitations, though. First,the benefits obtained from the use of some techniques that provide modular implemen-tation of crosscutting concerns are only seen when the whole crosscutting concern is

1SPL adoption strategies are discussed in Section 2.1.

31

Page 54: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

32 VARIATION TYPES AND IMPLEMENTATION PATTERNS

implemented with this technique. Consider a situation in which a single variation point,part of a crosscutting concern, is implemented using AOP, while the remaining variationpoints related to this concern are implemented with conditional compilation. Separationof concerns metrics probably will not show any advantage in using AOP to implementjust this single variation point. In fact, the level of concern scattering can even increase,as a new module will contribute to the implementation of this concern: an aspect. Sec-ond, it is also desirable to analyse the impact of compositions of patterns, in order tocompare the scalability of each technique. The impact of a sequence of applications ofpatterns is not equals to the sum of the impacts of each single application. Considera crosscutting concern that is scattered through ten classes. If we implement a singlevariation point of this concern with AOP and inheritance techniques, the impact on thevocabulary size will be the same for both cases: one extra module. On the other hand, ifwe implement all the variation points of this crosscutting concern with these techniques,the inheritance technique would result in a impact of ten extra modules (subclasses),whereas the AOP technique would still result in a impact of one extra module (a singleaspect). Although we focus on the evaluation of single application of patterns in the re-maining of this chapter, in Chapter 5 we evaluate the sequence of uses of many patterns,in order to implement a whole optional feature from BestLap, Arena feature.

The remaining of this chapter is organized as follows. In Section 4.1 to Section 4.5, wepresent the variation types of our catalog and, for each variation type, a set of variabilityimplementation patterns. Then, in Section 4.6, we make some final considerations aboutthe catalog of variation types and the set of variability implementation patterns.

4.1 VARIATION TYPE 1: VARIATION IN CLASS ATTRIBUTE

Where the variation occurs: Declaration of an attribute in a class definition.What varies: The initialization value of the attribute (alternative values) or the exis-tence of such attribute (optional attribute).

This variation type occurs when the implementation of a SPL requires a class attribute tohave different initialization values for different SPL instances, or when a class attribute isnot necessary to all instances. The first situation is often related to alternative features,where each variant imposes a different initialization value for an attribute. The formersituation often occurs when an attribute is part of the implementation of an optionalfeature and this attribute is not necessary in instances of the SPL where this feature isnot present.

For optional attributes, there are two reasons for not placing the definition of theseattributes in the artifacts that implement the commonality base of the SPL and, instead,place them within some artifact that is directly related to this variant feature. First, whenan attribute is not relevant for all the instances of a SPL, we are easing the reasoning andmaintenance activities in the SPL’s architecture when we remove this attribute from thecommonality base. Second, leaving this attribute in the commonality base can implies anextra overhead in the size of the packaged application in instances where this attribute

Page 55: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

4.1 VARIATION TYPE 1: VARIATION IN CLASS ATTRIBUTE 33

is unnecessary2.Listing 4.1 and Listing 4.2 show an example of Variation in Class Attribute where

alternative initialization values exist for an attribute. The example shows a part Main-Canvas class definition. In this example, Variation in Class Attribute occurs in twoattributes of MainCanvas class: SCREEN WIDTH and SCREEN HEIGHT, defined inlines 2 and 3. These two attributes are related to the ScreenSize concern. To illustratethe situation, we have shown only two alternative values for these attributes, however, inBestLap, we have eight different screen sizes (screen width and height combinations).

1 pub l i c c l a s s MainCanvas {2 pub l i c s t a t i c f i n a l i n t SCREEN WIDTH = 128 ;3 pub l i c s t a t i c f i n a l i n t SCREEN HEIGHT = 128 ;4 [ . . . ]5 }

Listing 4.1 Example of Variation in Class Attribute (a).

1 pub l i c c l a s s MainCanvas {2 pub l i c s t a t i c f i n a l i n t SCREEN WIDTH = 176 ;3 pub l i c s t a t i c f i n a l i n t SCREEN HEIGHT = 220 ;4 [ . . . ]5 }

Listing 4.2 Example of Variation in Class Attribute (b).

In Listing 4.3, we show examples of optional attributes. The attributes declared inlines 6, 9, and 12 store the sequence of keys that, when pressed, can enable cheats duringthe game play, like showing how many frames per second are being displayed on the screenor enabling all the levels of the game. Cheats are part of the Debug feature. They areused to help game testers to control the quality of the products, and are not intended tobe used by final users. These attributes, thus, do not make sense to exist in an instanceof the SPL deployed to end users, where the Debug feature should not be present.

In this section, we have introduced Variation in Class Attribute variation type anddiscussed two examples of this variation type in the BestLap SPL. In Section 4.1.1, wewill present some variability implementation patterns that can be used to deal with thisvariation type.

4.1.1 Patterns for Variation in Class Attribute

In this section we show the implementation patterns that can be used to implementoccurrences of Variation in Class Attribute. The first pattern proposed to address thisvariation type is Pattern 1.

2The might not be a great issue, though, since an efficient bytecode optimization tool could avoidthis unnecessary overhead.

Page 56: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

34 VARIATION TYPES AND IMPLEMENTATION PATTERNS

1 pub l i c c l a s s Resources {2 /** Show fp s on the s c r e en . */3 pub l i c s t a t i c f i n a l S t r ing CHEAT CODE FPS = [ . . . ] ;4 /** show fp s and memory on the s c r e en */5 pub l i c s t a t i c f i n a l S t r ing CHEAT CODE FPST = [ . . . ] ;6 /** unlock l e v e l s */7 pub l i c s t a t i c f i n a l S t r ing CHEAT CODE UNLOCK LEVELS = [ . . . ] ;8 [ . . . ]9 }

Listing 4.3 Example of Variation in Class Attribute (c).

Pattern 1. 〈Attribute Defined by Conditional Compilation〉

The attribute definition is placed in a #ifdef clause. The symbol used is for the #ifdefdirective represents the feature to which the attribute is related. Optionally, an arbitrarynumber of #elifdef tags may be present containing alternative declarations for theattribute and, at last, a #else tag may be present defining a default declaration forthe attribute. The source code must be preprocessed before any compilation tool beapplied. The attribute declaration present in the resulting pre-processed file will be theone related to the variant select during the pre-processing phase. If no symbol frompreprocessing directives surrounding the attribute matches with the set of symbols usedas input for the pre-processor and no default (#else directive) declaration exist, theattribute will not be included in the resulting source code file.

Pattern 1 clearly can handle both attributes with alternative initialization valuesand optional attributes. For optional attributes, no default declaration is defined, sothat when no match occurs, the attribute is omitted from the resulting pre-processedsource file. As a consequence of using conditional compilation, this pattern only supportscompile-type as variability binding time. Listing 4.4 shows Pattern 1 being used to handlethe variation in the initialization values for two attribute in MainCanvas class. Noticethat the attributes SCREEN WIDTH and SCREEN HEIGHT are handled as a pair.This situation happens because they vary their initial values due to the same variant.Thus, it is not necessary to treat the declaration of each attribute as a distinct pre-processing treatment. This reduces the number of lines in source files and increases theirunderstandability.

Listing 4.5 exemplifies how Pattern 1 can be used to implement optional attributes.Notice that, as in the example of Listing 4.4, the declaration of the optional attributescan be grouped into the same pre-processing condition if the belong to the same variant.

Variation in Class Attribute can also be implemented using Pattern 2, which de-fines an aspect for each alternative or optional attribute that is varying. This patternsupports biding of variabilities only at compile-type, due to the AspectJ’s weaving mech-anism. An example of Pattern 2 being used to handle variability in the attributes of

Page 57: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

4.1 VARIATION TYPE 1: VARIATION IN CLASS ATTRIBUTE 35

1 pub l i c c l a s s MainCanvas {2 //# i f d e f dev i c e s c r e en 128x1283 pub l i c s t a t i c f i n a l i n t SCREEN WIDTH = 128 ;4 pub l i c s t a t i c f i n a l i n t SCREEN HEIGHT = 128 ;5 //# e l i f d e f dev i c e s c r e en 176x2206 pub l i c s t a t i c f i n a l i n t SCREEN WIDTH = 176 ;7 pub l i c s t a t i c f i n a l i n t SCREEN HEIGHT = 220 ;8 //#e n d i f9 [ . . . ]

10 }Listing 4.4 Example of Attribute Defined by Conditional Compilation pattern to handle at-tributes with alternative initialization values.

1 pub l i c c l a s s Resources {2 //# i f d e f general debug mode3 /** Show fp s on the s c r e en . */4 pub l i c s t a t i c f i n a l S t r ing CHEAT CODE FPS = [ . . . ] ;5 /** show fp s and memory on the s c r e en */6 pub l i c s t a t i c f i n a l S t r ing CHEAT CODE FPST = [ . . . ] ;7 /** unlock l e v e l s */8 pub l i c s t a t i c f i n a l S t r ing CHEAT CODE UNLOCK LEVELS = [ . . . ] ;9 //#e n d i f

10 [ . . . ]11 }

Listing 4.5 Example of Attribute Defined by Conditional Compilation pattern to handle op-tional attributes.

Page 58: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

36 VARIATION TYPES AND IMPLEMENTATION PATTERNS

Pattern 2. 〈Attribute Defined by Inter-Type Declaration〉

The attribute is declared in an aspect as an inter-type declaration, being introducedinto the class. If the attribute needs to be directly accessed outside the aspect, it cannot be declared with the private modifier (even if it is accessed only inside the scopeof the class to which it is being introduced). Multiple (alternative) aspects can coexist,each defining the attribute with a different initial value. The choice of which aspect toinclude in each instance (or the choice to not include any aspect) is done at compiletime. These aspects are mutually-exclusive as they define an attribute with the samename to be introduced in a class through inter-type declarations.

MainCanvas class is shown in Listing 4.6, where alternative aspects (Screen128X128 andScreen176X220 ) introduce the SCREEN WIDTH and SCREEN HEIGHT attributesinto MainCanvas class. Each aspect defines a different initial value for these attributes.

1 pub l i c c l a s s MainCanvas {2 [ . . . ]3 }45 pub l i c aspect Screen128X128 {6 pub l i c s t a t i c f i n a l i n t MainCanvas .SCREEN WIDTH = 128 ;7 pub l i c s t a t i c f i n a l i n t MainCanvas .SCREEN HEIGHT = 128 ;8 [ . . . ]9 }

1011 pub l i c aspect Screen176X220 {12 pub l i c s t a t i c f i n a l i n t MainCanvas .SCREEN WIDTH = 176 ;13 pub l i c s t a t i c f i n a l i n t MainCanvas .SCREEN HEIGHT = 220 ;14 [ . . . ]15 }

Listing 4.6 Example of Attribute Defined by Inter-Type Declaration pattern to handle at-tributes with alternative initialization values.

Another example of Pattern 2 is shown in Listing 4.7, where DebugAspect introducesthree optional attributes into Resources class. There is no declaration of this attributesin Resources class. The optional aspect will only be weaved with Resources class whengenerating instances of BestLap for debug purposes.

Pattern 3 handles occurrences of Variation in Class Attribute by defining a propertyfile for each alternative initial values of an attribute. A good point of this pattern is that,in contrast to the two patterns presented previously, the variabilities can be bound atrun-time. A disadvantage of this pattern is that it can handle only cases of attributeswith different initialization values. It is not able to implement optional attributes alone,since the attribute declarations and the infrastructure necessary to read the values fromthe properties files are placed in the source code as commonality. Listing 4.8 shows thevariability in the attributes of MainCanvas class being implemented with Pattern 3.

Page 59: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

4.1 VARIATION TYPE 1: VARIATION IN CLASS ATTRIBUTE 37

1 pub l i c c l a s s Resources {2 [ . . . ]3 }45 aspect DebugAspect {6 /** Show fp s on the s c r e en . */7 [ . . . ] Resources .CHEAT CODE FPS = [ . . . ] ;8 /** show fp s and memory on the s c r e en */9 [ . . . ] Resources .CHEAT CODE FPST = [ . . . ] ;

10 /** unlock l e v e l s */11 [ . . . ] Resources .CHEAT CODE UNLOCK LEVELS = [ . . . ] ;12 }

Listing 4.7 Example of Attribute Defined by Inter-Type Declaration pattern to handle optionalattributes.

Pattern 3. 〈Attribute Initial Value Defined by Configuration File〉

No modifications are made to the declaration of the attribute. On the other hand,additional code is included in the program to read the initial value of the attribute froma properties file. An arbitrary number of alternative properties files can be used. Thecorrect properties files for each instance are read when the program starts, thus, thebiding of the variability occurs at run-time. This pattern alone is not able to handlesituations where the attribute is optional.

Page 60: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

38 VARIATION TYPES AND IMPLEMENTATION PATTERNS

1 pub l i c c l a s s MainCanvas {2 pub l i c s t a t i c i n t SCREEN WIDTH;3 pub l i c s t a t i c i n t SCREEN HEIGHT;45 s t a t i c {6 P r o p e r t i e s prop = new P r o p e r t i e s ( ) ;7 t ry {8 prop . load ( MIDletContro l l e r . g e t In s tance ( )9 . ge tC la s s ( )

10 . getResourceAsStream (”/ sc r e en . p r o p e r t i e s ” ) ) ;11 SCREEN WIDTH = I n t e g e r . pa r s e In t (12 prop . getProperty (” s c r e en . width ” ) ) ;13 SCREEN HEIGHT = I n t e g e r . pa r s e In t (14 prop . getProperty (” s c r e en . he ight ” ) ) ;15 } catch ( Exception e ) {16 e . pr intStackTrace ( ) ;17 }18 }19 [ . . . ]20 }212223 # Begin o f s c r e en . p r o p e r t i e s F i l e f o r 128 x128 Screens #24 sc r e en . width = 12825 sc r e en . he ight = 11726 # End o f s c r e en . p r o p e r t i e s F i l e f o r 128 x128 Screens #2728 # Begin o f s c r e en . p r o p e r t i e s F i l e f o r 176 x220 Screens #29 sc r e en . width = 17630 sc r e en . he ight = 22031 # End o f s c r e en . p r o p e r t i e s F i l e f o r 176 x220 Screens #

Listing 4.8 Example of Attribute Initial Value Defined by Configuration File pattern to handleattributes with alternative initialization values.

Page 61: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

4.1 VARIATION TYPE 1: VARIATION IN CLASS ATTRIBUTE 39

Pattern 4. 〈Optional Attribute Defined by Inheritance〉

The attribute is declared in a subclass that extends the behavior and structure of itsparent class to handle the variant concern. When refactoring an existing SPL to moveattributes from a parent class to one of its subclasses, all external references to the movedattribute should be updated. Moreover, some internal references to this attribute mightstill exist in the parent class and must be handled using other variability implementationpatterns (usually, also moved to the same subclass). Supports only occurrences ofVariation in Class Attribute where the attribute is optional.

Another pattern that can be used to handle occurrences of Variation in Class Attributeis Pattern 4. In contrast to the previous patterns, it offers support to implement onlyoptional attributes. This is a consequence of the fact that the (optional) attributes aredeclared in a subclass. As the attribute exist in the subclass (variability artifact), but notin the parent class (commonality artifact), it can be regarded as an optional attribute.An example of Pattern 4 is shown in Listing 4.9. The optional attributes are defined ina subclass of Resources class, ResourcesDebug.

1 pub l i c c l a s s Resources {2 [ . . . ]3 }45 pub l i c c l a s s ResourcesDebug extends Resources {6 /** Show fp s on the s c r e en . */7 pub l i c s t a t i c f i n a l S t r ing CHEAT CODE FPS = [ . . . ] ;8 /** show fp s and memory on the s c r e en */9 pub l i c s t a t i c f i n a l S t r ing CHEAT CODE FPST = [ . . . ] ;

10 /** unlock l e v e l s */11 pub l i c s t a t i c f i n a l S t r ing CHEAT CODE UNLOCK LEVELS = [ . . . ] ;12 }

Listing 4.9 Example of Attribute Defined by Subclass pattern to handle optional attributes.

Notice that in the examples of all the presented patterns, we have decided to groupattributes related to the same variant in the same entity (aspect, properties file or sub-class) or enclosed by the same pre-processing directive (in the conditional compilationpattern). This is indeed a good practice, as we are trying to achieve feature modularity.By placing every piece of source code relative to a variant into a single module (or smallset of modules), we are reducing the scattering of this variant. Even when we do notplace the attribute in a separated entity, as we do in the conditional compilation pattern,we are helping to reduce the tangling level in the class, by placing these attributes in thesame pre-processing group. In addition to the gains in feature modularity, this decisionclearly implies a smaller vocabulary size and less lines of source code.

Page 62: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

40 VARIATION TYPES AND IMPLEMENTATION PATTERNS

4.1.2 Evaluation of Patterns for Variation in Class Attribute

In order to compare the patterns proposed to handle Variation in Class Attribute, we haveimplemented the examples presented in the previous section. Then, we evaluated each ofthese implementations according to the comparison criteria we discusses previously.

As we define patterns that can address only cases of optional attributes (Pattern 4),patterns that can implement only alternative initialization values for attributes (Pat-tern 3), and patterns that can handle both situations (Pattern 1 and Pattern 2), we havedecided split the evaluation of these patterns in two parts. The next two sections showthe results of our evaluations. In Section 4.1.2.1, we discuss the evaluation of patternsused to implement variability in the initialization value for class attributes, whereas inSection 4.1.2.2 we discuss the evaluation of patterns used to implement optional classattributes.

4.1.2.1 Evaluation of Patterns for Alternative Initialization Values

We have implemented the variability in the screen size attributes with each of the threepatterns proposed to deal with alternative values for initialization of attributes (Pat-tern 1, Pattern 2, and Pattern 3) and then compared these implementations accordingto the criteria defined in Chapter 3.

One particularity of J2ME platform caused a major impact on the implementationof Pattern 3 (Attribute Initial Value Defined by Configuration File). J2ME platformdoes not natively support properties file like J2SE platform does. Thus, we had tocreate two new classes to provide a seamless support to this functionality (Propertiesand BufferedReader). This implied a great impact in the LOC and BS metrics for theexperiment using this pattern.

It is important to notice that the impact caused by the two additional classes requiredto use Pattern 3 on J2ME platform does not increase as the number of variation pointshandled by this pattern increases. Thus, we have a initial high impact to implement avariability using this pattern, and the subsequent applications of this pattern imposes amuch lower impact on the complexity and bytecode size of the SPL.

The source code of BestLap is composed by 15 classes. Implementing the variabilityin the screen size attributes of MainCanvas class with conditional compilation does notrequire any additional module, so this numbers remains the same for the implementa-tion of Pattern 1 (Attribute Defined by Conditional Compilation). To implement thisvariability with Pattern 2 (Attribute Defined by Inter-Type Declaration) and Pattern 3eight additional modules are required, since we have eight variants, each implementedin a distinct module. The implementation of the variability with Pattern 3 still requirestwo more classes, as we have already discussed. This information is shown in Table 4.2.The increase on VS metric for Pattern 2 and Pattern 3 is proportional to the numberof variants of the variability that we are implementing, considering that the modules inwhich the attributes will be placed (aspects or properties file) do not exist already.

Table 4.1 compares the values of LOC metric for the implementation of each of thethree patterns. The number of source code lines in MainCanvas class is highest when

Page 63: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

4.1 VARIATION TYPE 1: VARIATION IN CLASS ATTRIBUTE 41

we apply Pattern 1. This happens because we need to add a declaration of the vary-ing attribute for each the eight screen size variants. Each declaration has a differentinitialization value and is preceded by a specific conditional compilation directive. Thisvalue is much reduced for the implementation of Pattern 2, since the declarations of theattributes are omitted from the base class. For the implementation of Pattern 3, we donot need to include preprocessor directives. Instead, we need to include the code thatreads the properties file and initializes the attributes.

We can also notice that each aspect has a higher number of lines of code than theproperties files. This is due to the fact that we need to declare the aspect itself, whichincludes the package and import directives. Though, we should attend to the fact thatwe could have put the declaration of these attributes inside the scope of aspects thatalready existed in the SPL. Aspects are used to implement whole crosscutting concernsor variants in a modular way. Thus, we only need to declare a new aspect once for eachcrosscutting variant. Subsequent extractions of source code variabilities related to thesesame variants are put inside the existing aspects. So, subsequent applications of Pattern 2for ScreenSize variability would lead to less impact the complexity of the SPL in termsof LOC. This conclusion can be extended to VS metric too. Also notice that althoughBestLap has eight variants for the ScreenSize concern, and hence eight different screensize aspects and screen size properties files, we show the values of the LOC metric foronly one aspect and properties file since these values are the same for the all variants.

Table 4.1 also shows the impact of choosing each pattern on the total LOC of theSPL: 47 lines of code for Pattern 2 and 461 lines of code for Pattern 3, when comparedto Pattern 13. However, if we did not consider the additional classes (Properties andBufferedReader) during the metric calculation, the implementation of Pattern 3 wouldshow only a 9 lines of code increase from the implementation of Pattern 1.

The values for NOA metric are the same for Pattern 1 and Pattern 3, as we can seein Table 4.2. This value is reduced by 2 for the implementation of Pattern 2, since thetwo attributes are not declared in the class. On the other hand, the value of NOEDAmetric for this version is 2, since two attributes are being externally defined by inter-typedeclarations. Other complexity metrics are not relevant for this experiment, since nomodifications in the operations of MainCanvas class were made.

Extracting initialization values of attributes to aspects or properties files also increasesthe coupling in the class who owns the attribute. In the implementation of Pattern 2,MainCanvas class uses an attribute that is defined by an aspect (inter-type declaration)and thus is coupled to this aspect4. A similar situation happens in the implementation ofPattern 3. MainCanvas class has to access a properties file in order to read the attribute’sinitialization value, so it is also coupled to this properties file. One important detail tomention is that there is a set of alternative aspects or configuration files that can bechosen to provide an initialization value to the attributes. MainCanvas class, howeverdoes only depends on one of them to work properly. The others only provide an alternativeimplementation. So, we say that MainCanvas class is only coupled to one of them. There

3The Diff column represents the difference relative to the implementation of the fist pattern (originalBestLap version).

4The source code for the class does not compile if the aspect is not present.

Page 64: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

42 VARIATION TYPES AND IMPLEMENTATION PATTERNS

ArtifactPattern 1 Pattern 2 Pattern 3

LOC LOC Diff LOC DiffMainCanvas 607 582 -25 600 -7

Screen128X128 aspect (x8) - 9 9 - -

Screen128X128.properties (x8) - - - 2 2Properties - - - 166 166

BufferedReader - - - 286 286

Total - - 47 - 461

Table 4.1 LOC metric for patterns used to implement alternative initialization values for classattributes.

Pattern VSMainCanvas

NOA NOEDA CBC NCC NCV CScreenSize

Pattern 1 15 68 0 24 9 8Pattern 2 23 66 2 25 9 0Pattern 3 25 68 0 25 9 0

Table 4.2 VS metric and other metrics for comparing the impact of patterns used to implementalternative initialization values for attributes in MainCanvas class.

is, however, an implicit interface between MainCanvas class and the alternative aspects(in Pattern 2) or properties files (in Pattern 3). For the implementation of Pattern 2, animplicit interface defines the names of the attribute that will be introduced by an aspect.An aspect have to introduce this specific attribute thought an inter-type declaration,or the source code won’t compile. For Pattern 3, there is an implicit interface betweenMainCanvas class and the alternative properties file that defines the name of the propertythat holds the attribute’s initial value. These designs are not full modular, since theydo not provide clear explicit interfaces between interdependent modules. To improvemodular reasoning, it would be better if current programming languages offered supportfor explicit interface between modules in situations like this. Java interfaces are anexample of these interfaces, but they are limited to the object-oriented paradigm. Itwould be desirable to define an interface to abstract a set of alternative aspects or a setof alternative properties files. In fact, we had already identified the necessity of makingthis interface explicit in one of our previous works [38]. The values of CBC metric for

Screen128X128.aj Screen128X128.propertiesNOA 2 2CBC 1 0NCC 1 1

NCV CScreenSize 1 1

Table 4.3 Metric for showing the impact of use of Pattern 2 on Screen128X128 aspect andPattern 3 on Screen128X128 properties file.

Page 65: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

4.1 VARIATION TYPE 1: VARIATION IN CLASS ATTRIBUTE 43

MainCanvas class are shown in Table 4.2.Also notice that the aspects that introduce the attributes in MainCanvas class as

inter-type declarations are coupled to this class, since they need to reference the class towhich the attributes are introduced. The properties files, however, are not coupled toMainCanvas class. This information is shown in Table 4.3.

Pattern 2 and Pattern 3 show a great improve on separation of concern variants whencompared to Pattern 1. As Pattern 1 uses conditional compilation to implement thevariants of ScreenSize concern, it does not implement each variant in a distinct module.In the implementation of Pattern 2 and Pattern 3, MainCanvas class contributes to theimplementation of the ScreenSize concern. It does not, however, implement any of thevariants of this concern5, as they are implemented each on their own module: aspect orproperties file. This information shown in Table ??. In the implementation of Pattern 1,MainCanvas class holds the implementation of all the variants of ScreenSize concern.The cost for this separation of variants achieved by Pattern 2 and Pattern 3 is that theScreenSize concern is more scattered in the implementations of these patterns, as shownin Table 4.4. Even with a higher scattering for ScreenSize as whole, the situation withPattern 2 and Pattern 3 is better than the one with Pattern 1, since, in a SPL context,variant concern modularity is a highly desirable property, event if it implies in the higherlevel concern being spread in more modules.

Metric Pattern 1 Pattern 2 Pattern 3CDCScreenSize 7 15 15

CVDCScreen128x128 7 7 7CVDCScreen128x117 7 7 7CVDCScreen128x149 7 7 7CVDCScreen176x208 7 7 7CVDCScreen176x205 7 7 7CVDCScreen128x160 7 7 7CVDCScreen132x176 7 7 7CVDCScreen176x220 7 7 7

Table 4.4 Concern diffusion and variant diffusion metrics for the patterns used to implementalternative initialization values for class attributes.

In addition to the evaluation of the implementation artifacts in each experiment, it isalso interesting to analyse the impact of each pattern of the resulting application size foreach instance. Table 4.56 shows the values for BS metric for the instances of BestLap ineach one of the three experiments we have discussed so far. For the three experiments, wehave compiled the source code using the ABC compiler with the bytecode optimizationextension discussed in Section 2.2.4.

These numbers shows that the use of Pattern 2 results in a slightly higher bytecodesize for the SPL instances when compared to instances that were built using Pattern 1,

5No source code line of this class is specifically assigned to any variant of this concern.6σ stands for standard deviation.

Page 66: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

44 VARIATION TYPES AND IMPLEMENTATION PATTERNS

with an average increase of 91.76 bytes and a 22.82 standard deviation for the set ofsize differences. Pattern 3, however, resulted in a much higher increase on the bytecodesize, compared to Pattern 1, with an average increase of 4149.82 bytes and a standarddeviance of 39,59. This additional overhead is caused by the infrastructure required touse Pattern 3 in J2ME platform, which we discussed previously.

Pattern 1 Pattern 2 Pattern 3Instance Size Size Diff Size Diff

MOT1 72712 72808 96 76851 4139MOT2 85148 85249 101 89256 4108MOT3 72742 72839 97 76896 4154

S40 65129 65188 59 69419 4290S40M2 72793 72864 71 76966 4173

S40M2V3 72327 72414 87 76463 4136S60M1 85380 85477 97 89498 4118S60M2 84304 84393 89 88424 4120SAM1 66406 66544 138 70571 4165SAM2 80414 80539 125 84584 4170SE01 70984 71038 54 75110 4126SE02 84158 84248 90 88294 4136SE03 72386 72461 75 76544 4158SE04 72335 72442 107 76485 4150

SIEM2 72389 72444 55 76534 4145SIEM3 73068 73177 109 77188 4120SIEM4 72303 72413 110 76442 4139

Mean - - 91.76 - 4149.82σ - - 22.82 - 39.59

Table 4.5 BS metric for the patterns used to implement alternative initialization values forclass attributes.

By the analysis of these data, we can make some conclusions. First, by looking atthe complexity metrics, we can see that Pattern 1 performs better than the other two.Pattern 2 results in a slightly increase in the LOC metric, which is too low to be considereda problem. Pattern 3 resulted in a much higher increase in the LOC metric, but this iscaused by the two additional classes necessary to read the values from the propertiesfiles. If we do not count these classes as part of the SPL (by considering them as partof a development library, for example) the increase in the LOC metric would be similarto the increase of Pattern 2. Pattern 1 only shows a big advantage in complexity whencompared to the other two patterns when we consider the vocabulary size of the SPL. Inthe other two patterns, we need to define a module for each variant.

Regarding class modularity, we can notice that Pattern 1 outperforms Pattern 2 andPattern 3. The use of the latter two patterns resulted in more coupling between compo-nents. One cause for this higher level of coupling in the two latter patterns is the increase

Page 67: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

4.1 VARIATION TYPE 1: VARIATION IN CLASS ATTRIBUTE 45

in the number of modules.Another criterion in which the Pattern 1 is better than the other two is efficiency

in the generated bytecode size. This was already expected, though, since conditionalcompilation technique does not add any overhead to the size of the resulting applications.The average increase caused by the use of Pattern 2 was only 91.76 bytes in each instance.This very small increase is not relevant. Thus, the impact of Pattern 2 in the resultingbytecode is equivalent to the impact of Pattern 1. Pattern 3, however, show a very badperformance, with an average increase of 4149.82 bytes in each instance, when comparedto Pattern 1. Again, this overhead was due to the two additional classes necessary toread the values from the properties files.

The criterion in which Pattern 2 and Pattern 3 clearly outperform Pattern 1 is sep-aration of concerns. Although these two patterns had resulted in more scattering forthe ScreenSize concern, they were able to implement the variants of this concern in amodular way, reducing the tangling level.

4.1.2.2 Evaluation of Patterns for Optional Attributes

In this section, we compare the patterns that can be used to implement optional at-tributes in a class: Pattern 1 (Attribute Defined by Conditional Compilation), Pattern 2(Attribute Defined by Inter-Type Declaration), and Pattern 4 (Optional Attribute Definedby Inheritance). To our experiments, we have used the example shown in Section 4.1.1,where three attributes of Resources class, are part of the Debug optional concern, andthus are optional attributes.

The first criterion we use to compare the patterns is complexity. Table 4.7 showsthe vocabulary size of BestLap for the implementation of each pattern. As already wasexpected, the use of Pattern 2 and Pattern 4 resulted in an increase in the vocabularysize of the SPL. The first pattern adds an aspect (DebugAspect), which introduces theoptional attributes, whereas the latter creates a new class (ResourcesDebug), which con-tains the optional attributes. It should be noted, though, that Pattern 2 requires onlyone additional aspect for each optional concern. Pattern 4, however, requires a new sub-class to be created for each class where the concern defines an optional attribute. A SPLdeveloper must have this information in mind.

Regarding the number of lines of source code, the three patterns performed equally,as it is shown in Table 4.6. The differences in the LOC metric for the three experimentswere too low to be considered relevant. These patterns also do not result in a significantincrease in other complexity metrics, as shows Table 4.7 and Table 4.8.

Table 4.7 and Table 4.8 also show the impact of each pattern in the modularityof BestLap. The only pattern that implied additional coupling to Resources class wasPattern 2, as this class has externally defined attributes declared in DebugAspect. BothPattern 2 and Pattern 4 result in a low coupling to the new modules (DebugAspect andResourcesDebug), as shows Table 4.8. The use of Pattern 2 also resulted in an additionalcoupling in MainCanvas class (not shown in the tables). This was due to the fact thatMainCanvas class directly references the attributes declared in ResourcesDebug, creatingan additional coupling to this class.

Page 68: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

46 VARIATION TYPES AND IMPLEMENTATION PATTERNS

ArtifactPattern 1 Pattern 2 Pattern 4

LOC LOC Diff LOC DiffResources 1527 1522 -5 1522 -5

DebugAspect - 7 7 - -

ResourcesDebug - - - 6 6

Total - - 2 - 1

Table 4.6 LOC metric for patterns used to implement optional class attributes.

Pattern VS CDCDebugResources

NOA NOEDA CBC NCCPattern 1 15 3 307 0 27 10Pattern 2 16 3 304 3 28 9Pattern 4 16 3 307 0 27 9

Table 4.7 VS metric and other metrics for comparing the impact of use patterns used toimplement optional attributes in Resources class.

With respect to separation of concerns, Pattern 2 and Pattern 4 performed betterthan Pattern 1. The concern tangling level in Resources is lower for the experiments ofthese two patterns, when compared to Pattern 1, as we can see in Table 4.7. The tanglinglevel is same for DebugAspect and ResourcesDebug, as each of these modules implementsonly one concern, Debug. This information is shown in Table 4.8.

Another interesting result of the separation of concerns metrics was that diffusionof Debug concern over the components of BestLap was the same for the three cases(Table 4.7). Here, we can make the same observation we have made when we discussedVS metric in the beginning of this section. AOP gives us the possibility to place all theimplementation of a concern in a single module: an aspect. On the other hand, when weuse inheritance to implement variabilities, we need to create a new subclass for every classthat contributes to the implementation of a concern. Thus, although our experiments,which focus only on the optional attributes of a single class, have not shown a differencein the CDC metric for the implementations of Pattern 2 and Pattern 4, we should beaware to the fact that, when a whole concern is implemented using a single technique,AOP have a good chance to outperform inheritance in the reduction of scattering.

The results for the last comparison criterion, bytecode size, are summarized in Ta-ble 4.9. We have compiled the implementation of Pattern 1 and Pattern 2 using only theABC compiler with the bytecode optimization extension described in Section 2.2.4. For

NOA CBC NCCDebugAspect 3 1 1

ResourcesDebug 3 1 1

Table 4.8 Metric for showing the impact of use of Pattern 2 on DebugAspect and Pattern 4on ResourcesDebug class.

Page 69: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

4.1 VARIATION TYPE 1: VARIATION IN CLASS ATTRIBUTE 47

Pattern 4, we have compiled the source code with both ABC and CaesarJ compilers. Thereason for this decision was that the bytecode optimization extension for ABC allowed usto have the best performance in bytecode size. CaesarJ compiler, however, allows the useof mixins inheritance, which supports features composition in a scalable way. Althoughour experiment does not shows a case of features compositions, it is interesting to showthe impact on the sizes of the final applications, when using the CaesarJ compiler.

The table shows that the bytecode sizes of instances created using the implementationsof Pattern 2 and Pattern 4 (compiled with the ABC compiler) are very similar to theones of Pattern 1, which results in null impact. Pattern 4 even shows lower bytecodesizes for some instances. For Pattern 4 we can conclude that the impact on the bytecodesize was irrelevant. For Pattern 2, there was a small impact, but not too significant.

On the other hand, we have a considerable impact when we compile the experimentof Pattern 4 with the CaesarJ compiler. In this case, there was an average increase of340.29 in the bytecode size of the instances, when compared to the implementation usingPattern 1 compiled the ABC compiler.

Pattern 1 Pattern 2 Pattern 4 (ABC) Pattern 4 (CaesarJ)Instance Size Size Diff Size Diff Size Diff

MOT1 72704 72759 55 72711 7 73064 360MOT2 85131 85186 55 85138 7 85468 337MOT3 72737 72792 55 72749 12 73082 345

S40 66077 66126 49 66087 10 66507 430S40M2 72818 72857 39 72803 -15 73152 334

S40M2V3 72320 72369 49 72330 10 72669 349S60M1 86307 86370 63 86306 -1 86718 411S60M2 85240 85285 45 85237 -3 85567 327SAM1 66399 66471 72 66399 0 66707 308SAM2 81342 81411 69 81341 -1 81620 278SE01 71900 71963 63 71903 3 72300 400SE02 85090 85137 47 85098 8 85436 346SE03 72396 72447 51 72386 -10 72732 336SE04 72343 72390 47 72344 1 72687 344

SIEM2 72378 72431 53 72376 -2 72670 292SIEM3 73076 73127 51 73071 -5 73366 290SIEM4 72310 72365 55 72316 6 72608 298

Mean - - 54 - 1.58 - 340.29σ - - 8.35 - 7.17 - 41.27

Table 4.9 BS metric for the patterns used to implement optional attributes.

To summarize the discussion of this section, we come to the conclusion that withregard to complexity, Pattern 1 is slightly better than the other two. Pattern 4, however,can result in a higher vocabulary size, if the concern is spread through many classesthat have to be refined by new subclasses. The difference in the coupling metrics for

Page 70: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

48 VARIATION TYPES AND IMPLEMENTATION PATTERNS

the three patterns were also small. Pattern 2 and Pattern 4 can show a higher levelof coupling than Pattern 1, because they may require additional modules to be added.For the separation of concerns criteria, Pattern 2 performs better, followed by Pattern 4.Pattern 1, however, can result in a low level of tangling and scattering. Finally, thepatterns show no significant difference in the efficiency of the generated bytecode whenusing the ABC compiler. Pattern 4 can be used in conjunction with the CaesarJ compilerto allow features to be composed at class level using mixins. The use of CaesarJ compiler,though, imply in an extra overhead in the size of the resulting jar files and should beavoided if mixins are not necessary.

4.2 VARIATION TYPE 2: VARIATION IN CLASS HIERARCHY

Where the variation occurs: Declaration of a class.What varies: The superclass (defined by the extends keyword) or the set of imple-mented interfaces (defined by the implements keyword).

This variation type occurs when the inheritance hierarchy of a class varies among SPLinstances. This situation happens when a variant of a feature requires a class to extendanother class or to implement a set of new interfaces.

An example of this type of variability is shown in Listing 4.10, Listing 4.11, List-ing 4.12, and Listing 4.13. In the example, the superclass of MainCanvas class dependson the graphic API supported by the device to which the application will be deployed.If the device supports Nokia’s proprietary graphics API, the parent class of MainCan-vas must be FullCanvas class (Listing 4.10). If the device supports MIDP2 or Siemensgraphics API, the parent class must be GameCanvas class (Listing 4.12). If none ofthese graphics API are support, the parent class of MainCanvas must be Canvas class(Listing 4.13). These variants are part of the GraphicsCanvas concern, which deals withhow the game objects are drawn on the screen.

Another concern that appears in this example is the SE1 concern, which encompassall the particularities and known issues related to the Siemens SE01 mobile phone family.To build an instance to this product family, MainCanvas class not only has to extendfrom GameCanvas class, but also has to implement the CommandListener interface (List-ing 4.11). We consider these two concerns for this example, since both appear on thesame code location.

1 pub l i c c l a s s MainCanvas extends FullCanvas {2 [ . . . ]3 }

Listing 4.10 Example of Variation in Class Hierarchy (a).

1 pub l i c c l a s s MainCanvas extends GameCanvas implements2 CommandListener {3 [ . . . ]4 }

Listing 4.11 Example of Variation in Class Hierarchy (b).

Page 71: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

4.2 VARIATION TYPE 2: VARIATION IN CLASS HIERARCHY 49

1 pub l i c c l a s s MainCanvas extends GameCanvas {2 [ . . . ]3 }

Listing 4.12 Example of Variation in Class Hierarchy (c).

1 pub l i c c l a s s MainCanvas extends Canvas {2 [ . . . ]3 }

Listing 4.13 Example of Variation in Class Hierarchy (d).

In the next section, we present the variability implementation patterns that can beused to implement occurrences of Variation in Class Hierarchy.

4.2.1 Patterns for Variation in Class Hierarchy

The first pattern proposed to handle Variation in Class Hierarchy, Pattern 5, uses con-ditional compilation to implement the variants. The declaration of each class whoseparent class or set of implemented interfaces can vary is enclosed by a proper conditionalcompilation directive.

Pattern 5. 〈Class Hierarchy Defined by Conditional Compilation〉

The class declaration (class name, modifiers, extends list, implements list and throwslist) a is enclosed by conditional compilation directives. Alternative parent classes orsets of implemented interfaces can be defined by using multiple #elifdef directives and,optionally, a #else directive.

aThe class body is not enclosed by pre-processing directives.

Pattern 5 supports only compile-time as the biding time for variabilities. Listing 4.14shows Pattern 5 being used to implement the variability in the hierarchy of MainCanvasclass.

Another pattern proposed to handle this type of variability is Pattern 6. It canhandle occurrences of Variation in Class Hierarchy by placing the definition of the classhierarchy outside the class. The class definition contains only the class name and othermodifiers. The parent class, from which the class inherits, and the list of interfaces that itimplements are defined in an aspect, using AspectJ’s inter-type declarations mechanism.Listing 4.15 shows how the variability in MainCanvas class hierarchy can be implementedusing Pattern 6. This pattern allows variabilities to be bound at compile-time only.

In the next section, we discuss the evaluation of Pattern 5 and Pattern 6. ClassHierarchy Defined by Conditional Compilation

Page 72: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

50 VARIATION TYPES AND IMPLEMENTATION PATTERNS

1 //# i f d e v i c e g r a p h i c s c a n v a s n o k i a u i2 pub l i c c l a s s MainCanvas extends FullCanvas {3 //# e l i f s k u i d s e 14 pub l i c c l a s s MainCanvas extends GameCanvas implements5 CommandListener {6 //# e l i f dev i c e g raph i c s canvas midp27 | | d e v i c e g r a p h i c s c a n v a s s i e m e n s8 pub l i c c l a s s MainCanvas extends GameCanvas {9 //# e l s e

10 pub l i c c l a s s MainCanvas extends Canvas {11 //#e n d i f1213 [ . . . ]14 }

Listing 4.14 Example of Class Hierarchy Defined by Conditional Compilation pattern to han-dle variability in the hierarchy structure of MainCanvas class.

Pattern 6. 〈Class Hierarchy Defined by Inter-Type Declaration〉

The variabilities related to the hierarchy structure of a class are implemented in aspects,as inter-type declarations, using the declare parents directive, which can change both theparent class or the set of implement interface of a class. Aspects that define the parentclass for the same (sub)class are mutually exclusive, because of the single inheritancerestriction of Java language. Aspects that change the set of implemented interfaces ofa class (by adding new interfaces to this set), can be combined, as a class is allowed toimplement an arbitrary number of interfaces in Java language.

Page 73: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

4.2 VARIATION TYPE 2: VARIATION IN CLASS HIERARCHY 51

1 pub l i c c l a s s MainCanvas {2 [ . . . ]3 }45 pub l i c aspect Midp2CanvasAspect {6 d e c l a r e parents : MainCanvas extends GameCanvas ;7 }89 pub l i c aspect NokiaCanvasAspect {

10 d e c l a r e parents : MainCanvas extends FullCanvas ;11 }1213 pub l i c aspect SiemensCanvasAspect {14 d e c l a r e parents : MainCanvas extends GameCanvas ;15 }1617 pub l i c aspect SE01Aspect {18 d e c l a r e parents : MainCanvas implements CommandListener ;19 }

Listing 4.15 Example of Class Hierarchy Defined by Inter-Type Declaration pattern to handlevariability in the hierarchy structure of MainCanvas class

4.2.2 Evaluation of Patterns for Variation in Class Hierarchy

The first impact resultant of the use of Pattern 6 (Class Hierarchy Defined by Inter-TypeDeclaration) over Pattern 5 (Class Hierarchy Defined by Conditional Compilation) is theincrease in the vocabulary size of the SPL. As each variant is implemented in a separatedmodule, the vocabulary size is increased. It is the price paid for achieving separation ofconcerns. As we discussed before, however, the value of VS metric is not proportionalto the number of variation points. Instead, it is proportional to the number of concernvariants, as each variants is confined in a distinct aspect. Table 4.10 shows the values ofVS metric for the implementations of the two patterns.

VSPattern 5 15Pattern 6 19

Table 4.10 VS metric for the patterns used to implement Variation in Class Hierarchy.

We can also notice a small increase in the total number of lines of source code of theBestLap SPL when we chose Pattern 6 over Pattern 5. Table 4.11 shows the increase foreach implementation asset as well as the overall increase for the SPL. The overall increaseis a consequence of the extra overhead caused by the declarations of the new aspects. Onthe other hand, the choice for Pattern 6 over Pattern 5 results in a decrease in the LOCof MainCanvas class. This happens because the alternative hierarchy for MainCanvasclass, in addition to the required preprocessing tags are not present in the source code of

Page 74: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

52 VARIATION TYPES AND IMPLEMENTATION PATTERNS

MainCanvas class when we choose Pattern 6. Also notice that if we do not consider theadditional overhead caused by the header of the aspects, we would get an overall decreaseon the total LOC for Pattern 6 over Pattern 5, instead of an increase, because would notneed to define conditional compilation directives. This is the situation when the aspectsfor each variant are already defined, before applying Pattern 6 to handle variability inthe hierarchy of a class.

ArtifactPattern 5 Pattern 6

LOC LOC DiffMainCanvas 607 600 -7

Midp2CanvasAspect - 6 6NokiaCanvasAspect - 6 6

SiemensCanvasAspect - 6 6SE01Aspect - 6 6

Total - - 17

Table 4.11 Complexity metrics for the patterns used to implement Variation in Class Hierar-chy.

Other complexity metrics, like NOA, NOO and WOC are not relevant in this con-text, since Pattern 5 and Pattern 6 affects only the inheritance hierarchy of a class, notinterfering in its attributes or operations.

With respect to modularity, there was no difference in the values of the CBC metric forMainCanvas class when we compare the implementation with both patterns. Pattern 6resulted in each aspect being coupled to two other modules. These values can be seen inTable 4.12.

ArtifactCBC

Pattern 5 Pattern 6MainCanvas 24 24

Midp2CanvasAspect - 2NokiaCanvasAspect - 2

SiemensCanvasAspect - 2SE01Aspect - 2

Table 4.12 CBC metric for the implementations of Pattern 5 and Pattern 6.

When using AOP to handle a variation point, it is expected to increase the separationof concerns of a program. In our experiment, however, the version of BestLap where thevariability in the hierarchy of MainCanvas class is implemented using Pattern 6 is notbetter, when comparing separation of concerns, than the one in which this variability isimplemented using Pattern 5, as we can see in Table 4.13 and Table 4.14. The version ofPattern 6 even had a worse performance when comparing the diffusion of the variants ofGraphicsCanvas concern.

Page 75: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

4.2 VARIATION TYPE 2: VARIATION IN CLASS HIERARCHY 53

These results may, at first, seem controversial, but they are a consequence of theevaluation of single applications of patterns. Although this approach allows us evaluatethe impact of every single pattern on the quality attributes of a SPL, it also can hide somebenefits of some techniques, like AOP, which are only full achieved when we implementa whole concern using only this technique.

Metric Pattern 5 Pattern 6CDCSE01 6 6

CDCGraphicsCanvas 2 3CVDCNokiaCanvas 2 3CVDCMidp2Canvas 2 3CVDCSiemensCanvas 2 3

Table 4.13 Concern diffusion and variant diffusion metrics for the implementations of Pattern 5and Pattern 6.

ArtifactPattern 5 Pattern 6

NCC NCV CGraphicsCanvas NCC NCV CGraphicsCanvas

MainCanvas 9 3 9 3Midp2CanvasAspect - - 1 1NokiaCanvasAspect - - 1 1

SiemensCanvasAspect - - 1 1SE01Aspect - - 1 -

Table 4.14 Concern tangling and variant tangling metrics for the implementations of Pattern 5and Pattern 6.

Pattern 5 is clearly more efficient than Pattern 6 in the size of the deployed appli-cations, as we can see in Table 4.15. The instances built from the experiment wherePattern 6 was used had an average increase of 178.35 bytes in their BS metric, whencompared to the instances create by the version of Pattern 5.

Making a summary of the evaluation, we can notice that Pattern 5 performed betterthan Pattern 6 in the complexity and modularity criteria. On the other hand, the advan-tage of Pattern 5 over Pattern 6 in the complexity criterium tends to be reduced as thenumber of pattern applications grows. Also, the results of separation of concern metricsshowed no benefits for Pattern 6 over Pattern 5. However, as we argued previously, thefull benefits of AOP are only seen when all the variation points related to a concern arehandled using this technique. We leave the demonstration that AOP technique performsbetter than conditional compilation in separation of crosscutting concerns to Chapter 5.Finally, Pattern 5 is better than Pattern 6 when the efficiency in bytecode size criterionis chosen.

Page 76: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

54 VARIATION TYPES AND IMPLEMENTATION PATTERNS

Pattern 5 Pattern 6Instance Size Size Diff

MOT1 72712 72893 181MOT2 85148 85317 169MOT3 72742 72921 179

S40 65129 65300 171S40M2 72793 72999 206

S40M2V3 72327 72510 183S60M1 85380 85553 173S60M2 84304 84471 167SAM1 66406 66564 158SAM2 80414 80574 160SE01 70984 71150 166SE02 84158 84332 174SE03 72386 72581 195SE04 72335 72535 200

SIEM2 72389 72553 164SIEM3 73068 73255 187SIEM4 72303 72502 199

Mean - - 178.35σ - - 14.28

Table 4.15 BS metric for the implementations of Pattern 5 and Pattern 6.

4.3 VARIATION TYPE 3: VARIATION IN THE WHOLE BODY OF A METHOD

Where the variation occurs: In the body of a method.What varies: The whole body of the method.

This variation type occurs when a variability requires the whole behavior of a method tochange. This can be done by defining a behavior to a method that has an empty bodyor is not defined in the commonality base (positive variability), canceling the behavior ofan existing method (negative variability) or changing the behavior of a method definedin the commonality base (positive and negative variability).

An example of this variation type is shown in Listing 4.16, Listing 4.17, and List-ing 4.18. In this example, the behavior of the playSound method of SoundEffects class isdifferent among the instances of BestLap. The variability in the example is part of theSound API alternative concern. The devices to which BestLap is deployed can supportone of the following sound APIs: NokiaAPI, SamsumgAPI, and MMAPI. Dependingon which sound API is supported by the device, a different set of commands must beexecuted when the playSound method is invoked. In the next section, we show somevariability implementation patterns for handling occurrences of Variation in the WholeBody of a Method.

Page 77: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

4.3 VARIATION TYPE 3: VARIATION IN THE WHOLE BODY OF A METHOD 55

1 pub l i c c l a s s SoundEf fects {2 [ . . . ]3 p r i v a t e void playSound ( i n t soundIndex ) {4 t h i s . sounds [ soundIndex ] . play (SOUND LOOP[ soundIndex ] ) ;5 }6 }

Listing 4.16 Example of Variation in the Whole Body of a Method (a).

1 pub l i c c l a s s SoundEf fects {2 [ . . . ]3 p r i v a t e void playSound ( i n t soundIndex ) {4 t h i s . sounds [ soundIndex ] . play (SOUND LOOP[ soundIndex ] , VOLUME) ;5 }6 }

Listing 4.17 Example of Variation in the Whole Body of a Method (b).

1 pub l i c c l a s s SoundEf fects {2 [ . . . ]3 p r i v a t e void playSound ( i n t soundIndex ) {4 try {5 t h i s . sounds [ soundIndex ] . s t a r t ( ) ;6 } catch ( MediaException e ) {7 e . pr intStackTrace ( ) ;8 }9 }

10 }

Listing 4.18 Example of Variation in the Whole Body of a Method (c).

Page 78: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

56 VARIATION TYPES AND IMPLEMENTATION PATTERNS

4.3.1 Patterns for Variation in the Whole Body of a Method

The first pattern used to implement Variation in the Whole Body of a Method is Pattern 7.This pattern encloses the body of the method with conditional compilation directives,allowing alternative behaviors for the method, or canceling the behavior of the methodwhen necessary (by defining an empty method body). An example of the variabilityin playSound method of SoundEffects class implemented with this pattern is shown inListing 4.19.

Pattern 7. 〈Whole Body of a Method Defined by Conditional Compilation〉

The whole body of the method is enclosed by conditional compilation directives. Alter-native behaviors to the method can be defined by using multiple #elifdef directives ora #else directive.

1 pub l i c c l a s s SoundEf fects {2 [ . . . ]3 p r i v a t e void playSound ( i n t soundIndex ) {4 //# i f d ev i c e s ound ap i nok i a5 t h i s . sounds [ soundIndex ]6 . play (SOUND LOOP[ soundIndex ] ) ;7 //# e l i f dev ice sound api samsung8 t h i s . sounds [ soundIndex ]9 . play (SOUND LOOP[ soundIndex ] , VOLUME) ;

10 //# e l i f device sound api mmapi11 try {12 t h i s . sounds [ soundIndex ] . s t a r t ( ) ;13 } catch ( MediaException e ) {14 e . pr intStackTrace ( ) ;15 }16 //#e n d i f17 }18 }

Listing 4.19 Example of Whole Body of a Method Defined by Conditional Compilation patternto handle alternative behaviors for playSound method in SoundEffects class.

Pattern 8 implements Variation in Whole Body of a Method by using inter-type dec-larations to define the methods inside the lexical scope of aspects. As the inter-typedeclaration mechanism is used, the whole method (not just its body) is declared insidethe aspect. This pattern makes it possible to implement optional methods in a SPL. Itis not possible, however, to use this pattern to implement negative variability, as it isnot possible to remove attributes or method from a class using inter-type declarations.On the other hand, negative variabilities, in most of the cases, can be transformed intopositive ones [23]. Listing 4.20 shows an example of this pattern in action.

Page 79: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

4.3 VARIATION TYPE 3: VARIATION IN THE WHOLE BODY OF A METHOD 57

Pattern 8. 〈Whole Body of a Method Defined by Inter-type Declaration〉

The method declaration is omitted from class. An aspect (or set of alternative aspects)introduces the method into the class using the inter-type declarations mechanism. As-pects that introduces methods with the same signature are mutually exclusive.

1 pub l i c c l a s s SoundEf fects {2 [ . . . ]3 }45 pub l i c aspect SoundPlayerMMAPIAspect {6 pub l i c void SoundEf fects . playSound ( i n t soundIndex ) {7 try {8 t h i s . sounds [ soundIndex ] . s t a r t ( ) ;9 } catch ( MediaException e ) {

10 e . pr intStackTrace ( ) ;11 }12 }13 }1415 pub l i c aspect SoundPlayerNokiaAspect {16 pub l i c void SoundEf fects . playSound ( i n t soundIndex ) {17 t h i s . sounds [ soundIndex ]18 . play ( t h i s .SOUND LOOP[ soundIndex ] ) ;19 }20 }2122 pub l i c aspect SoundPlayerSamsungAspect {23 pub l i c void SoundEf fects . playSound ( i n t soundIndex ) {24 t h i s . sounds [ soundIndex ] . play25 ( t h i s .SOUND LOOP[ soundIndex ] , SoundEf fects .VOLUME) ;26 }27 }

Listing 4.20 Example of Whole Body of a Method Defined by Inter-type Declaration patternto handle alternative behaviors for playSound method in SoundEffects class.

Page 80: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

58 VARIATION TYPES AND IMPLEMENTATION PATTERNS

In contrast to Pattern 8, Pattern 9 leaves the method declaration inside the class.This pattern is useful when there is a default behavior for a method, which changes onlyfor a small subset of the SPL instances. When no default behavior is defined, a stubmethod7 must be declared in the class. This stub method is necessary because it definesthe joinpoint that will be affected by the around advice. One advantage of this pattern isthat it supports the implementation of negative variabilities. An around advice can cancelthe default behavior of a method. Another advantage is that this pattern, with somesmall modifications, could allow variability bind at run-time, using CaesarJ’s dynamicdeployment mechanism. This is not possible to be done with Pattern 8, as CaesarJ doesnot support inter-type declarations. Listing 4.21 shows how the variability in playSoundmethod can be implemented using Pattern 9.

Pattern 9. 〈Whole Body of a Method Defined by Around Advice〉

The method is declared in the class, defining a default behavior. The behavior of themethod can be changed by an optional aspect, or a set of alternative aspects, that usearound advices to override the default behavior of the method.

Pattern 10 relies on the classical Strategy design pattern to implement occurrences ofVariation in the Whole Body of a Method. Strategy design pattern uses a combinationof delegation and inheritance techniques to accomplish this task. This pattern supportsvariabilities to be bound at run-time. An object factory is necessary to instantiate thecorrect class. For this purpose, the Abstract Factory design pattern can be used [33]. Aimplementation of this pattern is shown in Listing 4.22.

Pattern 11 uses inheritance technique to override the default behavior of the methodin a subclass. Just as in Pattern 9, this pattern allows the implementation of negativevariabilities and requires the method to be declared in the parent class, even if it isdeclared as a stub method. An example of this pattern is shown in Listing 4.23.

7A method with an empty body.

Page 81: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

4.3 VARIATION TYPE 3: VARIATION IN THE WHOLE BODY OF A METHOD 59

1 pub l i c c l a s s SoundEf fects {2 [ . . . ]3 p r i v a t e void playSound ( i n t soundIndex ) { }4 }56 pub l i c aspect SoundPlayerMMAPIAspect {7 void around ( SoundEf fects se , i n t soundIndex ) :8 execut ion ( void SoundEf fects . playSound ( i n t ) )9 && args ( soundIndex ) && t h i s ( se ) {

10 try {11 se . sounds [ soundIndex ] . s t a r t ( ) ;12 } catch ( MediaException e ) {13 e . pr intStackTrace ( ) ;14 }15 }16 }1718 pub l i c aspect SoundPlayerNokiaAspect {19 void around ( SoundEf fects se , i n t soundIndex ) :20 execut ion ( void SoundEf fects . playSound ( i n t ) )21 && args ( soundIndex ) && t h i s ( se ) {22 c t h i s . sounds [ soundIndex ]23 . play ( c t h i s .SOUND LOOP[ soundIndex ] ) ;24 }25 }2627 pub l i c aspect SoundPlayerSamsungAspect {28 void around ( SoundEf fects se , i n t soundIndex ) :29 execut ion ( void SoundEf fects . playSound ( i n t ) )30 && args ( soundIndex ) && t h i s ( se ) {31 se . sounds [ soundIndex ] . play32 ( se .SOUND LOOP[ soundIndex ] , SoundEf fects .VOLUME) ;33 }34 }

Listing 4.21 Example of Whole Body of a Method Defined by Around Advice pattern to handlealternative behaviors for playSound method in SoundEffects class.

Pattern 10. 〈Whole Body of a Method Defined by Strategy〉

This variability implementation pattern uses the Strategy design pattern [33] to definean alternative set of behaviors to an specific method. Invocations to the method aredelegated to an abstract type. Implementations of this abstract type perform the variantbehaviors.

Page 82: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

60 VARIATION TYPES AND IMPLEMENTATION PATTERNS

1 pub l i c c l a s s SoundEf fects {2 [ . . . ]3 p r i v a t e ISoundPlayer soundPlayer ;4 pub l i c SoundEf fects ( ) {5 [ . . . ]6 t h i s . soundPlayer =7 SoundPlayerFactory . getSoundPlayer ( t h i s ) ;8 }9 p r i v a t e void playSound ( i n t soundIndex ) {

10 soundPlayer . playSound ( soundIndex ) ;11 }12 }1314 pub l i c i n t e r f a c e ISoundPlayer {15 pub l i c void playSound ( i n t soundIndex ) ;16 }1718 pub l i c c l a s s SoundPlayerMMAPI implements ISoundPlayer {19 p r i v a t e SoundEf fects se ;20 pub l i c SoundPlayerMMAPI( SoundEf fects se ) {21 t h i s . se = se ;22 }23 pub l i c void playSound ( i n t soundIndex ) {24 [ . . . ]25 }26 }27 pub l i c c l a s s SoundPlayerNokia implements ISoundPlayer {28 p r i v a t e SoundEf fects se ;29 pub l i c SoundPlayerNokia ( SoundEf fects se ) {30 t h i s . se = se ;31 }32 pub l i c void playSound ( i n t soundIndex ) {33 [ . . . ]34 }35 }36 pub l i c c l a s s SoundPlayerSamsung implements ISoundPlayer {37 p r i v a t e SoundEf fects se ;38 pub l i c SoundPlayerSamsung ( SoundEf fects se ) {39 t h i s . se = se ;40 }41 pub l i c void playSound ( i n t soundIndex ) {42 [ . . . ]43 }44 }

Listing 4.22 Example of Whole Body of a Method Defined by Strategy pattern to handlealternative behaviors for playSound method in SoundEffects class.

Page 83: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

4.3 VARIATION TYPE 3: VARIATION IN THE WHOLE BODY OF A METHOD 61

Pattern 11. 〈Whole Body of a Method Defined by Method Override〉

One or more subclasses refine the class where the variation occurs and override themethod behavior. A declaration of the method must exist in the parent class, defining adefault behavior in its bodya. The method can not be declared with the final modifier.

aIf no default behavior exists, an empty or abstract method must be declared in the parent class.

1 pub l i c ab s t r a c t c l a s s SoundEf fects {2 [ . . . ]3 protec t ed abs t r a c t void playSound ( i n t soundIndex ) ;4 }56 pub l i c c l a s s SEMMAPI extends SoundEf fects {7 protec t ed void playSound ( i n t soundIndex ) {8 try {9 t h i s . sounds [ soundIndex ] . s t a r t ( ) ;

10 } catch ( MediaException e ) {11 e . pr intStackTrace ( ) ;12 }13 }14 }1516 pub l i c c l a s s SENokia extends SoundEf fects {17 protec t ed void playSound ( i n t soundIndex ) {18 t h i s . sounds [ soundIndex ] . play (SOUND LOOP[ soundIndex ] ) ;19 }20 }2122 pub l i c c l a s s SESamsung extends SoundEf fects {23 protec t ed void playSound ( i n t soundIndex ) {24 t h i s . sounds [ soundIndex ] . play (SOUND LOOP[ soundIndex ] , VOLUME) ;25 }26 }

Listing 4.23 Example of Whole Body of a Method Defined by Method Override pattern tohandle alternative behaviors for playSound method in SoundEffects class.

Page 84: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

62 VARIATION TYPES AND IMPLEMENTATION PATTERNS

4.3.2 Evaluation of Patterns for Variation in the Whole Body of a Method

With regard to the complexity criterion, the use of Pattern 10 (Whole Body of a MethodDefined by Strategy) resulted in the most expensive solution. It requires more additionalmodules than the other patterns, as show the results of VS metric (Table 4.17). It alsoresulted in the highest increase in the values of LOC metric, shown in Table 4.16. Thisimpact was also revealed by the results of NOA metric for SoundEffects class (Table 4.17).Pattern 10 requires an additional attribute in this class, in order to delegate the executionof playSound method to another object.

ArtifactPattern 7 Pattern 8 Pattern 9 Pattern 10 Pattern 11

LOC LOC Diff LOC Diff LOC Diff LOC DiffSoundEffects 313 300 -13 302 -11 305 -8 301 -12

Other Artifacts - 30 30 36 36 53 53 35 35

Total - - 17 - 25 - 45 - 23

Table 4.16 LOC metric for patterns used to implement Variation in the Whole Body of aMethod.

Pattern VSSoundEffects

NOO WOC NOEDO NOA CBC LCOO NCCPattern 7 15 12 20 0 20 19 4 11Pattern 8 18 11 18 1 20 20 7 11Pattern 9 18 12 20 0 20 19 18 11Pattern 10 20 12 20 0 21 21 18 11Pattern 11 19 12 20 0 20 19 18 11

Table 4.17 VS metric and metrics for the patterns used to implement Variation in the WholeBody of a Method on SoundEffects class.

Pattern 9 (Whole Body of a Method Defined by Around Advice) and Pattern 11 (WholeBody of a Method Defined by Method Override) are somewhat equivalent in this criterion.The use of Pattern 11 implied in an addition of one in the VS metric, though. Thisadditional module is the factory necessary to the instantiation of SoundPlayer class (orone of its subclasses).

The use of Pattern 8 (Whole Body of a Method Defined by Inter-type Declaration) re-sulted in less complexity for SoundPlayer class than the use of Pattern 9 and Pattern 11.In Pattern 8, the declaration of the operation is omitted in SoundEffects class, reducingthe values of NOO and WOC metrics for this class8. The complexity, however, is re-flected in the alternative aspects (SoundPlayerMMAPIAspect, SoundPlayerNokiaAspectand SoundPlayerSamsungAspect). These aspects are also present in the implementa-tion of Pattern 9. The results of WOC metric indicates that the operations defined in

8Although the values of NOO and WOC metrics are lower, the value of NOEDO metric shows thatone operation is being externally defined for this class when Pattern 8 is used.

Page 85: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

4.3 VARIATION TYPE 3: VARIATION IN THE WHOLE BODY OF A METHOD 63

the aspects that are part of the implementation of Pattern 8 are less complex than theoperations defined in the aspects for the implementation of Pattern 9 (Table 4.18).

Pattern 7 (Whole Body of a Method Defined by Conditional Compilation) resulted inless impact on results of the complexity metrics than all the other patterns.

ArtifactPattern 8 Pattern 9

NOO WOC CBC NOO WOC CBCSoundPlayerMMAPIAspect 1 2 3 1 3 3SoundPlayerNokiaAspect 1 2 2 1 3 2

SoundPlayerSamsungAspect 1 2 2 1 3 2

Table 4.18 Metrics for Pattern 8 and Pattern 9.

ArtifactPattern 10

NOO WOC NOA CBCSoundPlayerMMAPI 2 4 1 4SoundPlayerNokia 2 4 1 3

SoundPlayerSamsung 2 4 1 3ISoundPlayer 1 2 0 0

SoundPlayerFactory 1 2 0 5

Table 4.19 Metrics for Pattern 10.

ArtifactPattern 11

NOO WOC NOA CBCSEMMAPI 1 2 0 3SENokia 1 2 0 2

SESamsung 1 2 0 2SEFactory 1 1 0 4

Table 4.20 Metrics for Pattern 11.

Pattern 10 also got the worst results in the modularity criterion (Table 4.17), asSoundEffects class is coupled to an interface and a factory class in the implementationof this pattern. Pattern 8 also resulted in an additional coupling for SoundEffects classbecause this class references a method that is declared in an aspect, as an inter-typedeclaration (externally defined operation). The implementations of Pattern 7, Pattern 9,and Pattern 11 resulted in no impact on the CBC metric for SoundEffects class, whencompared to Pattern 7.

Table 4.17 also shows a variation in values of LCOO metric among the differentversions. However, it is difficult to generalize these results, since the metric depends onthe number of operations in the module, and what set of instance variables each operationreferences. The values of CBC metric for the artifacts that are specific to some patternsare shown in Table 4.18, Table 4.19, and Table 4.20.

Page 86: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

64 VARIATION TYPES AND IMPLEMENTATION PATTERNS

These experiments did not show advantages with respect to separation of concerns.This happened because the Sound API concern is scattered in other parts of SoundEffectsclass. Thus, the implementation of a single variation point in this class will not showthe benefits of techniques capable of modularizing crosscutting concerns. As Table 4.17shows, none of the versions resulted in a reduction on concern scattering. We know,however, that techniques like AOP are expected to get better results if the whole SoundAPI concern (which is crosscutting) is implemented using this technique.

The results of BS metric for all the patterns discussed in this section are shownin Table 4.21 and Table 4.22. Among the versions compiled with the ABC compiler,Pattern 9 showed the worst results, followed by Pattern 10. The difference betweenthe results of Pattern 8 and Pattern 11 is very small. When comparing the version ofPattern 11 compiled with the ABC compiler with the version compiled with CaesarJcompiler, we noticed that the latter had a great overhead in the size of the generatedinstances. This shows again that CaesarJ compiler must be avoided when none of thefeatures of CaesarJ language are necessary and the size of the final application is a veryimportant issue.

Pattern 7 Pattern 8 Pattern 9Instance Size Size Diff Size Diff

MOT1 72712 73319 607 73779 1067MOT2 85148 85725 577 86201 1053MOT3 72742 73339 597 73827 1085

S40 65129 65312 183 66204 1075S40M2 72793 73410 617 73874 1081

S40M2V3 72327 72918 591 73398 1071S60M1 85380 85970 590 86453 1073S60M2 84304 84899 595 85384 1080SAM1 66406 66992 586 67480 1074SAM2 80414 80622 208 81534 1120SE01 70984 71583 599 72052 1068SE02 84158 84752 594 85224 1066SE03 72386 72985 599 73476 1090SE04 72335 72933 598 73414 1079

SIEM2 72389 72553 164 72563 174SIEM3 73068 73259 191 73251 183SIEM4 72303 72494 191 72494 191

Mean - - 475.70 919.41σ - - 186.43 - 341.32

Table 4.21 BS metric for the patterns used to implement Variation in the Whole Body of aMethod (a).

As a summary of our analysis, we conclude that Pattern 7 should be chosen if thepriority is efficiency in the bytecode generation, whereas Pattern 9 and Pattern 10 should

Page 87: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

4.4 VARIATION TYPE 4: VARIATION IN THE BEGINNING OR END OF METHOD BODY 65

be avoided. With regard to the complexity criterion, the pattern that had the worseresults was Pattern 10. This experiment was not sufficient to evaluate correctly theseparation of concerns criterion, but we expect that successive applications of the AOPpatterns (Pattern 8 and Pattern 8) would outperform the use other patterns.

Pattern 10 Pattern 11 Pattern 11 (CaesarJ)Instance Size Diff Size Diff Size Diff

MOT1 73530 818 73248 536 74321 1609MOT2 85961 813 85671 523 86726 1578MOT3 73561 819 73273 531 74354 1612

S40 65921 792 65646 517 66736 1607S40M2 73642 849 73344 551 74406 1613

S40M2V3 73155 828 72842 515 73894 1567S60M1 86190 810 85938 558 86998 1618S60M2 85132 828 84844 540 85846 1542SAM1 67240 834 66948 542 67948 1542SAM2 81191 777 80906 492 81884 1470SE01 71800 816 71541 557 72628 1644SE02 84980 822 84686 528 85719 1561SE03 73211 825 72916 530 73953 1567SE04 73169 834 72871 536 73912 1577

SIEM2 72559 170 72619 230 72907 518SIEM3 73259 191 73315 247 73594 526SIEM4 72495 192 72546 243 72840 537

Mean - 706.94 - 480.94 - 1393.41σ - 242.46 - 112.64 - 402.90

Table 4.22 BS metric for the patterns used to implement Variation in the Whole Body of aMethod (b).

4.4 VARIATION TYPE 4: VARIATION IN THE BEGINNING OR END OF METHODBODY

Where the variation occurs: In the beginning or end of a method body or constructorbody.What varies: A block of consecutive source code lines.

This variation type can be found when a block of consecutive lines of source codelocated at the extremities of a method or constructor body belongs to the implementationof an optional or alternative feature of the SPL. Thus, this block of source code lines mightvary depending on which features are being considered.

An example of such variability type is shown in Listing 4.24. In the example, themethod gc computeLevelScore, defined in GameScreen class, is responsible for calculating

Page 88: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

66 VARIATION TYPES AND IMPLEMENTATION PATTERNS

the game score at the end of each level. The code in lines 8 and 9 belongs to theimplementation of Arena feature, which sends high scores to a game server if an internetconnection is present. As Arena is an optional feature, this block of code may be executedor not, depending on whether Arena feature is chosen. In the next section, we present aset of patterns that can be used to implement this variation type.

1 pub l i c c l a s s GameScreen extends Screen implements Runnable {2 [ . . . ]3 p r i v a t e void gc computeLevelScore ( ) {4 t h i s . s c r l e v e l T o t a l S c o r e = [ . . . ] ;5 i f ( t h i s . s c r l e v e l T o t a l S c o r e < 0) {6 t h i s . s c r l e v e l T o t a l S c o r e = 0 ;7 }8 NetworkFacade . s e tSco r e ( t h i s . s c r l e v e l T o t a l S c o r e ) ;9 NetworkFacade . s e t L e v e l ( t h i s . gc getCurrentLeve l ( ) ) ;

10 }11 }

Listing 4.24 Example of Variation in the Beginning or End of Method Body.

4.4.1 Patterns for Variation in the Beginning or End of Method Body

The first pattern proposed to address this variation type, Pattern 12, uses conditionalcompilation to define a variation at the end or beginning of the body of a method. Anexample of this pattern in action is shown in Listing 4.25.

Pattern 12. 〈Variation in the Beginning or End of Method Body Defined by Condi-tional Compilation〉

The block of source code lines located at the extremity of the method or constructorbody is enclosed by conditional compilation directives. Alternative behaviors to thisblock can be defined by using multiple #elifdef directives or a #else directive.

Pattern 13 uses AOP to handle occurrences of Variation in Beginning or End ofMethod Body. The execution of methods are valid joinpoints in AspectJ language. Anaspect can intercept executions of a specific method and execute some arbitrary codebefore or after this joinpoint. Advices declared in different aspects can be combined,aiming at enabling composition of features. The order in which the advices are executeddepends on the precedence relations among aspects. This pattern originally supportsonly compile-type as the binding time for the variabilities. However, with some smallmodifications (using cclasses instead of aspects) it can enable variabilities to be boundat run-time, using the dynamic deployment mechanism of CaesarJ. An example of thispattern is listed in Listing 4.26.

The third pattern proposed to deal with this variation type is Pattern 14. It relies oninheritance and method override to add the extra behavior before or after a method is

Page 89: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

4.4 VARIATION TYPE 4: VARIATION IN THE BEGINNING OR END OF METHOD BODY 67

1 pub l i c c l a s s GameScreen extends Screen implements Runnable {2 [ . . . ]3 p r i v a t e void gc computeLevelScore ( ) {4 t h i s . s c r l e v e l T o t a l S c o r e = [ . . . ] ;5 i f ( t h i s . s c r l e v e l T o t a l S c o r e < 0) {6 t h i s . s c r l e v e l T o t a l S c o r e = 0 ;7 }8 //# i f f e a t u r e a r e n a e n a b l e d9 NetworkFacade . s e tSco r e ( t h i s . s c r l e v e l T o t a l S c o r e ) ;

10 NetworkFacade . s e t L e v e l ( t h i s . gc getCurrentLeve l ( ) ) ;11 //#e n d i f12 }13 }

Listing 4.25 Example of Variation in the Beginning or End of Method Body Defined by Con-ditional Compilation

Pattern 13. 〈Variation in the Beginning or End of Method Body Defined by After/Be-fore Advice〉

An after or before advice becomes responsible for executing the alternative or optionalbehavior before or after the execution of the method. The pointcut is defined for execu-tion of the method in question. Aspects that implement optional or alternative variantsare weaved with the base classes of the system when the variants are to be includedduring the build of an instance.

1 pub l i c c l a s s GameScreen extends Screen implements Runnable {2 [ . . . ]3 p r i v a t e void gc computeLevelScore ( ) {4 t h i s . s c r l e v e l T o t a l S c o r e = [ . . . ] ;56 i f ( t h i s . s c r l e v e l T o t a l S c o r e < 0) {7 t h i s . s c r l e v e l T o t a l S c o r e = 0 ;8 }9 }

10 }1112 pub l i c aspect Arena {13 a f t e r ( GameScreen gs ) :14 execut ion ( void GameScreen . gc computeLevelScore ( ) )15 && t h i s ( gs ) {16 NetworkFacade . s e tSco r e ( gs . s c r l e v e l T o t a l S c o r e ) ;17 NetworkFacade . s e t L e v e l ( gs . gc getCurrentLeve l ( ) ) ;18 }19 }

Listing 4.26 Example of Variation in the Beginning or End of Method Body Defined by Af-ter/Before Advice

Page 90: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

68 VARIATION TYPES AND IMPLEMENTATION PATTERNS

executed. Java programming language allows a subclass to invoke methods defined in itsparent class by using the super reserved word. Thus, it is possible define a subclass thatoverrides a specific method, execute some arbitrary block of commands and then invokethe overriden method from the superclass (variation at the beginning of a method body).In a similar way, the invocation to the overriden method can be placed before the block ofcommands (variation at the end of a method body). Pattern 14 may permit variabilitiesto be bound at run-time. A factory is necessary to instantiate the correct class (the parentclass or one of its subclasses) when necessary. An example of this pattern being used toimplement Variation in the Beginning or End of Method Body is listed in Listing 4.27.

Pattern 14. 〈Variation in the Beginning or End of Method Body Defined byInheritance〉

A subclass overrides the method where the variation occurs, executing the optional oralternative behavior and invoking the execution of the method in the parent class justafter or before. The source code in the commonality base holds references to the parentclass only. As Java language allows instances of subclasses to be used in any contextthat instances of the parent class are expected, the other artifacts in the commonalitybase of the SPL are agnostic to the existence of the variability.

1 pub l i c c l a s s GameScreen extends Screen implements Runnable {2 [ . . . ]3 p r i v a t e void gc computeLevelScore ( ) {4 t h i s . s c r l e v e l T o t a l S c o r e = [ . . . ] ;56 i f ( t h i s . s c r l e v e l T o t a l S c o r e < 0) {7 t h i s . s c r l e v e l T o t a l S c o r e = 0 ;8 }9 }

10 }1112 pub l i c c l a s s GameScreenArena extends GameScreen {13 protec t ed void gc computeLevelScore ( ) {14 super . gc computeLevelScore ( ) ;15 NetworkFacade . s e tSco r e ( t h i s . s c r l e v e l T o t a l S c o r e ) ;16 NetworkFacade . s e t L e v e l ( t h i s . gc getCurrentLeve l ( ) ) ;17 }18 }

Listing 4.27 Example of Variation in the Beginning or End of Method Body Defined by In-heritance

Page 91: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

4.4 VARIATION TYPE 4: VARIATION IN THE BEGINNING OR END OF METHOD BODY 69

4.4.2 Evaluation of Patterns for Variation in the Beginning or End of MethodBody

When comparing the patterns according to the complexity criterion, Pattern 14, showedto be the most complex solution. It required two more modules than Pattern 12 andone more than Pattern 13 (Table 4.23). It also resulted in more source code lines thanthe two other patterns, as shows Table 4.24. The three patterns performed equally inother complexity metrics for GameScreen class, so we do not show a comparison of theseresults.

Pattern VS CDC ArenaGameScreen

NCCPattern 12 15 7 8Pattern 13 16 7 7Pattern 14 17 8 7

Table 4.23 Metrics for patterns used to implement Variation in the Beginning or End ofMethod Body.

ArtifactPattern 12 Pattern 13 Pattern 14

LOC LOC Diff LOC DiffGameScreen 2509 2505 -4 2505 -4ArenaAspect - 10 10 - -

GameScreenArena - - - 10 10GameScreenFactory - - - 11 11

Total - - 6 - 17

Table 4.24 LOC metric for patterns used to implement Variation in the Beginning or End ofMethod Body.

Other complexity metrics for the artifacts specific for the implementations of Pat-tern 13 and Pattern 14 are shown in Table 4.25. Each of these artifacts defines only oneoperation and is coupled to only two other modules, with the exception of GameScreen-Factory, which is coupled to three other modules

Artifact NOA NOO WOC CBCArenaAspect 0 1 2 2

GameScreenArena 0 1 1 2GameScreenFactory 0 1 1 3

Table 4.25 Other complexity metrics and CBC metric for patterns used to implement Varia-tion in the Beginning or End of Method Body.

All the patterns also had the same results in the coupling metrics for GameScreenclass. Again, we do not show these metrics here, since their values were the same for

Page 92: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

70 VARIATION TYPES AND IMPLEMENTATION PATTERNS

all patterns and no comparative analysis is necessary. It should be noted however that,although these patterns had the same performance for coupling metrics in this specificexample, this is not a general rule. When extracting some blocks of source code fromone module to another, the coupling in the origin module can be changed. CBC metricfor the artifacts specific of the implementations of Pattern 13 and Pattern 14 is shown inTable 4.25.

By these values, we conclude that Pattern 14 is the one that imply more impact inthe overall complexity and coupling between components of the SPL. This is caused bythe factory necessary to instante the correct class for each SPL instance.

GameScreen contains only one variation point related to Arena feature. When thisvariation point is extracted to another module (subclass or aspect), the number of con-cerns implemented by GameScreen class is reduced. Table 4.23 shows how the tanglinglevel is reduced in GameScreen class when Pattern 13 or Pattern 14 is used to extractthe variability related to Arena feature from this class.

In this experiment, we do not visualize benefits in terms of concern scattering forArena, as shows Table 4.23. We argue, however, that if all the variation points from thisfeature were handled using AOP patterns, the CDC metric would reduce very much, asits implementation would be concentrated in the aspect. We evaluate this hypothesis inChapter 5.

Pattern 12 Pattern 13 Pattern 14Instance Size Size Diff Size Diff

MOT1 72712 73626 914 73189 477MOT2 85148 86062 914 85625 477MOT3 72742 73663 921 73222 480

S40 65129 66071 942 65622 493S40M2 72793 73725 932 73279 486

S40M2V3 72327 73246 919 72808 481S60M1 85380 86302 922 85875 495S60M2 84304 85231 927 84796 492SAM1 66406 66410 4 66639 233SAM2 80414 80402 -12 80647 233SE01 70984 71925 941 71476 492SE02 84158 85082 924 84654 496SE03 72386 73321 935 72868 482SE04 72335 73285 950 72821 486

SIEM2 72389 73316 927 72858 469SIEM3 73068 74009 941 73572 504SIEM4 72303 73235 932 72797 494

Mean - - 819.58 - 457.05σ - - 300.90 - 82.24

Table 4.26 BS metric for for the patterns used to implement Variation in the Beginning orEnd of Method Body.

Page 93: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

4.5 VARIATION TYPE 5: VARIATION IN A STRUCTURE AROUND METHOD BODY 71

When we compare the patterns against the efficiency in bytecode generation criterion,we see that although the use of Pattern 13 tends to result in less complexity in the sourcecode, less coupling and more separation of concerns than the use of Pattern 14, the latterresulted in a smaller BS for the final products. This information is shown in Table 4.26.

4.5 VARIATION TYPE 5: VARIATION IN A STRUCTURE AROUND METHODBODY

Where the variation occurs: The body of a method.What varies: A conditional or loop structure that surrounds the method body.

This variation type occurs when a block of commands in a method body, which rep-resents a commonality, is surrounded by a conditional or loop structure, which representsa variability. An example of such variation type is listed in Listing 4.28. The commonal-ity block in line 109, denoted by [COMMONALITY BLOCK], is a sequence of commandsthat represent a commonality in the body of changeMenuType method. The if-else struc-ture (lines 3 to 8, and 11) is a variability related to Arena feature, which means thatthis structure must not be present in instances of BestLap where Arena is not supported.In Section 4.5.1, we present three patterns that can be used to implement this variationtype.

1 pub l i c c l a s s GameMenu {2 p r i v a t e void changeMenuType ( ) {3 i f ( t h i s . menuType == POST SCORE MENU) {4 t h i s . menuTitlePosY = [ . . . ] ;5 t h i s . message = n u l l ;6 t h i s . f i r s tOpt ionPosY = [ . . . ] ;7 t h i s . gapBetweenOption = [ . . . ] ;8 }9 e l s e {

10 [COMMONALITY BLOCK]11 }12 }13 [ . . . ]14 }

Listing 4.28 Example of Variation in a Structure Around Method Body.

4.5.1 Patterns for Variation in a Structure Around Method Body

Pattern 15 uses conditional compilation to handle the variability in the structure that sur-rounds the commonality block. Listing 4.29 shows this pattern being used to implementthe variability related to Arena feature in GameMenu class.

9In fact, the real block occupies several lines in the source code of BestLap. For simplicity, weabstracted the real sequence of commands, as they are not relevant to the understanding of the problem.

Page 94: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

72 VARIATION TYPES AND IMPLEMENTATION PATTERNS

Pattern 15. 〈Structure Around Method Body Defined by Conditional Compilation〉

The structure that surrounds the commonality block of the method is enclosed by condi-tional compilation directives. The structure will only be compiled as part of the sourcecode in instances of the SPL where the optional feature is present.

1 pub l i c c l a s s GameMenu {2 p r i v a t e void changeMenuType ( ) {3 //# i f f e a t u r e a r e n a e n a b l e d4 i f ( t h i s . menuType == POST SCORE MENU) {5 t h i s . menuTitlePosY = [ . . . ] ;6 t h i s . message = n u l l ;7 t h i s . f i r s tOpt ionPosY = [ . . . ] ;8 t h i s . gapBetweenOption = [ . . . ] ;9 }

10 e l s e {11 //#e n d i f12 [COMMONALITY BLOCK]13 //# i f f e a t u r e a r e n a e n a b l e d14 }15 //#e n d i f16 }17 [ . . . ]18 }

Listing 4.29 Example of Structure Around Method Body Defined by Conditional Compilation.

Page 95: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

4.5 VARIATION TYPE 5: VARIATION IN A STRUCTURE AROUND METHOD BODY 73

AOP can also be used to implement this variation type. Pattern 16 defines an aroundadvice on the execution of the method to add the optional surround structure in instanceswhere the related feature is present. The optional aspect is weaved with the class whenbuilding instances where this feature is present. An example of use of Pattern 16 is shownin Listing 4.30.

Pattern 16. 〈Structure Around Method Body Defined by Around Advice〉

The method definition in the class contains only the commonality block in its body. Theoptional surrounding structure is implemented in an aspect, as an around advice, whichcalls the proceed command to execute the commonality block. Aspects that implementoptional structures around method bodies are weaved with the base classes of the systemonly when the related variants are present in the instance being built.

1 pub l i c c l a s s GameMenu {2 p r i v a t e void changeMenuType ( ) {3 [COMMONALITY BLOCK]4 }5 [ . . . ]6 }78 pub l i c aspect ArenaAspect {9 void around (GameMenu gm) :

10 execut ion ( void GameMenu . changeMenuType ( ) )11 && t h i s (gm) {12 i f (gm. menuType == GameMenu .POST SCORE MENU) {13 gm. menuTitlePosY = [ . . . ] ;14 gm. message = n u l l ;15 gm. f i r s tOpt ionPosY = [ . . . ] ;16 gm. gapBetweenOption = [ . . . ] ;17 }18 e l s e {19 proceed (gm) ;20 }21 }22 }

Listing 4.30 Example of Structure Around Method Body Defined by Around Advice.

Pattern 17 uses inheritance to override the method in a subclass and add the surround-ing structure (variability). The super keyword, allows the subclass to invoke methodsfrom the parent class, and thus, to execute the commonality block. An example is shownin Listing 4.31.

In the following section, we discuss the impact of each of these patterns in the qualityattributes of the SPL.

Page 96: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

74 VARIATION TYPES AND IMPLEMENTATION PATTERNS

Pattern 17. 〈Structure Around Method Body Defined by Inheritance〉

A subclass is defined to handle the variability. The method definition in the parentclass contains only the commonality block in its body. This method is overriden inthe subclass, which implements the optional surrounding structure and uses the superkeyword to invoke the overriden method from the parent class.

1 pub l i c c l a s s GameMenu {2 p r i v a t e void changeMenuType ( ) {3 [COMMONALITY BLOCK]4 }5 [ . . . ]6 }78 pub l i c c l a s s GameMenuArena extends GameMenu {9 pub l i c void changeMenuType ( ) {

10 i f ( t h i s . menuType == GameMenu .POST SCORE MENU) {11 t h i s . menuTitlePosY = [ . . . ] ;12 t h i s . message = n u l l ;13 t h i s . f i r s tOpt ionPosY = [ . . . ] ;14 t h i s . gapBetweenOption = [ . . . ] ;15 }16 e l s e {17 super . changeMenuType ( ) ;18 }19 }20 }

Listing 4.31 Example of Structure Around Method Body Defined by Inheritance.

Page 97: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

4.5 VARIATION TYPE 5: VARIATION IN A STRUCTURE AROUND METHOD BODY 75

4.5.2 Evaluation of Patterns for Variation in a Structure Around Method Body

The use of Pattern 16 and Pattern 17 resulted in more complex implementations thanPattern 15 for this variation type. Pattern 16 requires an aspect for the variability tobe implemented whereas Pattern 17 required both a subclass and a factory class. Thisinformation is shown in Table 4.27. The extra overhead from the class can also be noticedin the values of LOC metric for the experiments, as shows Table 4.28.

VSPattern 15 15Pattern 16 16Pattern 17 17

Table 4.27 VS metric for patterns used to implement Variation in a Structure Around MethodBody.

ArtifactPattern 15 Pattern 16 Pattern 17

LOC LOC Diff LOC DiffGameMenu 2509 2505 -4 2505 -4

ArenaAspect - 10 10 - -GameMenuArena - - - 10 10

GameMenuFactory - - - 11 11

Total - - 6 - 17

Table 4.28 LOC metric for patterns used to implement Variation in a Structure AroundMethod Body.

No significant impacts have been observed in other complexity metrics for GameMenu.All the three patterns resulted in the same values of NOA, NOO, and WOC metricsfor this class. The same can be said about modularity metrics (CBC and LCOO) forGameMenu class: the use of all patterns resulted in the same values for these metrics.Again, we warn that although we see no difference in the results of the coupling metricsfor this example, this is not a general conclusion, as the extraction of blocks of commandsfrom one module to another can change the coupling in both.

The results of complexity metrics and CBC metric for the additional artifacts requiredby Pattern 16 (ArenaAspect) and Pattern 17 (GameMenuArena and GameMenuFactory)are shown in Table 4.29.

Also, there was not benefits in terms of separation of concerns in applying Pattern 16or Pattern 17 to handle this single variation point. Arena is a crosscutting concern thatis highly tangled in GameMenu class. Extracting just a single variation point to a newmodule does not solve the problem and even increases the level of scattering.

When comparing these patterns against the efficiency in bytecode generation criterion,we see that Pattern 15 performed better, as it does not imply any overhead. Pattern 16resulted in greater negative impact in this criterion than Pattern 17. The detailed valuesfor BS metric can be seen in Table 4.30.

Page 98: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

76 VARIATION TYPES AND IMPLEMENTATION PATTERNS

Artifact NOA NOO WOC CBCArenaAspect 0 1 2 2

GameMenuArena 0 1 1 2GameMenuFactory 0 1 1 3

Table 4.29 Complexity metrics for comparing the impact of use patterns used to implementVariation in a Structure Around Method Body in artifacts specific of Pattern 16 and Pattern 17.

Pattern 15 Pattern 16 Pattern 17Instance Size Size Diff Size Diff

MOT1 72733 73613 880 73273 540MOT2 85160 86033 873 85698 538MOT3 72763 73633 870 73301 538

S40 65151 66046 895 65696 545S40M2 72846 73715 869 73372 526

S40M2V3 72340 73223 883 72875 535S60M1 85406 86293 887 85949 543S60M2 84321 85200 879 84877 556SAM1 66418 66421 3 66667 249SAM2 80420 80421 1 80662 242SE01 71009 71907 898 71544 535SE02 84178 85058 880 84719 541SE03 72416 73302 886 72958 542SE04 72359 73246 887 72895 536

SIEM2 72410 73282 872 72935 525SIEM3 73098 73993 895 73637 539SIEM4 72336 73198 862 72864 528Mean - - 777.64 - 503.41σ - - 283.38 - 94.45

Table 4.30 BS metric for for the patterns used to implement Variation in a Structure AroundMethod Body.

Page 99: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

4.6 FINAL CONSIDERATIONS 77

4.6 FINAL CONSIDERATIONS

In this section, we make some comments and consideration about our variability imple-mentation model.

4.6.1 Beyond the Catalog of Variation Types

One important characteristic about our model is that we suggest a set patterns for ad-dressing specific variation types, where each pattern has its advantages and drawbacks.One important question to be made is what the developer of a SPL should do when hetries to implement a variation that is not present in our catalog of variabilities. Theanswer is the following: whenever a variation to be implemented does not match anyvariation type from the catalog, the software developer should refactor the source code ofthe SPL in order to expose the variation in a way that it can be treated by some patternof the catalog.

Consider an example where a variation occurs in a sequence of commands in thescope of a method body. The variation represents only a small part of the method body,which means the execution of the method must be the same for all the instances of thisSPL, except for some optional or alternative sequence of commands in the middle of thismethod. The variation is not located at the extremities of the method body, in a way thatit could be treated as a case of Variation in the Beginning or End of Method Body. Onepossible solution is to consider the whole body of the method as a variation, at use anyof the patterns proposed to address Variation in the Whole Body of a Method. Indeed,this solution is very inefficient, since it results in replication of source code, which is notthe objective of the SPL approach. The best solution in this case would be to apply a therefactoring Extract Method [31] in order to move only the sequence of commands relatedto the variability to a new method. Then, the variability can be treated as a case ofVariation in the Whole Body of a Method, without resulting in code replication.

Sometimes, even when an variation matches one of the variation types of the catalog,a refactoring is necessary. Consider a variation that consists of a sequence of commandslocated in the end of a method body, which uses some local variables declared in themethod. It is, truly a case of Variation in the Beginning or End of Method Body, butthe patterns that uses inheritance or AOP to implement this variability (Pattern 13 andPattern 14) can not be used in this situation. Local variables of methods are not visiblein aspects nor in subclasses. If a developer wants to use Pattern 13 or Pattern 14 inthis situation, a refactoring must be applied first. One possible solution, would be totransform the local variables in class instance variables.

Finally, we do not prove that our catalog of variation types is complete. That is, wedo guarantee that every possible variation can be transformed into a variation type ofour catalog. Investigation towards a complete set of variation types for implementationartifacts of SPLs is indeed a very important future work.

Page 100: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

78 VARIATION TYPES AND IMPLEMENTATION PATTERNS

4.6.2 Crosscutting Variabilities vs Non-crosscutting Variabilities

The comparative evaluation we performed in this chapter focus on individual applicationsof patterns to address a single variation point. This comparison is not enough when wedeal with variabilities that are crosscutting.

As we discussed, the full benefits of techniques proposed to handle crosscutting con-cerns are only seen when the whole concern is implement with these techniques. In Chap-ter 5, we conduct an experiment where a full crosscutting variability in implemented usingsome techniques. One important characteristic of our model is that developers focus onthe implementation of variabilities at single locations in the source code, but they shouldbe aware of the nature of the variabilities. If the the variation being implemented ispart of a crosscutting variability, techniques like AOP should be considered, even if theytemporally implies worse results for implementing that single variation point.

4.6.3 Quantification in Aspect-Oriented Programming

Crosscutting concerns can be homogeneous or heterogenous [13]. In homogeneous cross-cutting concerns, one advice is related to many joinpoints, whereas in heterogenous cross-cutting concerns each advice is bounded to one or few joinpoints. AspectJ supportsthe implementation of homogeneous crosscutting concerns because of the quantificationmechanism provided by its pointcut model.

Quantification allows homogeneous crosscutting concerns to be implemented withoutsource code replication. If a software developer implements a homogeneous crosscuttingvariability using only our variation types catalog and patterns, the quantification mecha-nism of AspectJ would not be used. In fact, at the end of the variability implementation,the aspect that implements the variability would have many advices that perform thesame operations.

We did not faced this problem in our experiments, as the application we took as casestudy does not contains homogenous crosscutting variabilities. This problem can happenin other domains, though. One possible solution is to refactor the aspects [45, 22], inorder explore AspectJ’s quantification mechanism, after all variation points are handled.

4.7 SUMMARY

In this chapter we have presented our catalog of variation types. For each variation typewe have presented a set of variability implementation patterns. We compared the setof patterns for each variation type in order to easy the decisions of software developersabout which pattern to chose, given their priorities (for example, source code complexityor final application size). After, we made some considerations about this model. In thenext chapter, we will evaluate the use of this model to implement a complete crosscuttingvariability of BestLap.

Page 101: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

CHAPTER 5

EVALUATION

In order to validate the patterns we have discussed in the previous chapter, we haveimplemented a whole optional feature of BestLap SPL using different variability enablingtechniques. As we said previously, all the variabilities of BestLap were implementedwith conditional compilation. We then, created different versions of this SPL in whichthe chosen feature was implemented using one particular variability enabling technique.After, we compared the different versions using the metrics and criteria from Chapter 3.This case study had three objectives:

1. To evaluate patterns composition. In Chapter 4, we discussed how the qualityattributes of a SPL can be affected when we apply a single pattern to handle anspecific variation point. We, however, did not evaluate how these quality attributescould be affected when we compose a set of different patterns.

2. To evaluate efficacy of each technique for implementing crosscutting vari-abilities in a modular way. As we discussed in Chapter 4, it is impossible toevaluate efficacy of a technique to deal with the modularization of crosscutting con-cerns without implementing all the variation points that are part of one concern.

3. To evaluate how the catalog of variation types and set of patterns canguide the implementation of a feature. We verified that our catalog is reallyuseful to guide the implementation of variabilities in SPLs.

For this case study, we have chosen the optional feature Arena from BestLap. Thisfeature allows players to send their high scores to a network server and to compare theirperformance with other players in a global ranking. At the end of each level, the playeris asked if he wants to log into the remote server and post his score. The player can alsoaccess the data stored in Arena server from the game‘s main menu. Figure 5.1 showssome captures of screens related to the Arena feature.

We have decided to use Arena feature for our case study for three reasons:

1. It is a non-trivial concern, as it represents 14.74% of the total lines of source codein the original version of BestLap.

2. It is an important feature of this SPL, since it is present in fifteen of the seventeenBestLap instances.

3. It is a crosscutting concern. The implementation of Arena is highly scatteredthrough the classes of BestLap in its original version (implemented with condi-tional compilation). It is present in seven of the fifteen classes and has a DoS valueof 0.6237. Not only it is scattered, but it is also implemented in a tangled way.

79

Page 102: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

80 EVALUATION

Figure 5.1 Screen captures from Arena optional feature.

Table 5.1 shows the values of some metrics for the original version of BestLap, whereall the variabilities, including the Arena feature, are implemented with the conditionalcompilation technique. The vocabulary size (VS metric) for this version of BestLap is 15,and the value for the total LOC is 10,345. From all the classes shown in the table, onlyMainCanvas, MIDletController, Resources, GameScreen, MainScreen, GameMenu andNetworkFacade classes contain some block of code related to Arena feature. NetworkFa-cade is the only class that has the implementation of Arena feature as its main purpose.The other six classes although not directly related to Arena, are somehow affected bythis feature because of its crosscutting nature.

Class LOC NOA NOO WOC LCOO CBC NCCLevelManager 615 46 22 33 183 10 2MainCanvas 596 68 29 52 300 26 9

MIDletController 115 7 13 14 54 12 2Resources 1527 307 48 114 1128 27 10SESiemens 94 17 6 10 15 12 1

SoundEffects 313 20 12 20 4 17 11GameScreen 2509 244 59 93 1127 17 8MainScreen 1341 64 34 75 431 16 5GameMenu 1315 146 22 31 131 12 6

NetworkFacade 409 28 13 21 60 20 27ArrayList 118 3 10 17 0 4 1

Screen 701 18 43 119 901 15 1BVGAnimator 364 23 13 30 66 12 1

Sprite 144 24 12 18 52 8 1BytePNG 187 10 15 30 103 7 1

Table 5.1 Metrics for BestLap SPL where Arena feature is implemented using conditionalcompilation technique.

The first step in our experiment was to implement Arena feature with Java inheritancemechanism. As part of this task, we have defined five new subclasses: MainCanvasArena,MIDletControllerArena, GameScreenArena, MainScreenArena, GameMenuArena, whichextend MainCanvas, MIDletController, GameScreen, MainScreen, GameMenu classes

Page 103: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

EVALUATION 81

respectively. After, we used some of the patterns from Chapter 4 to extract all theparts of the source code related to Arena feature to these subclasses1. No extraction inNetworkFacade class was necessary, since this class is only included in a product whenArena feature is selected for that instance. In addition to the mentioned subclasses,it was also necessary to define factories to instantiate the correct classes (superclass orsubclass) depending on whether Arena feature is selected for the instance being built.For this task, we used the Abstract Factory design pattern [33].

Some metrics for this version of BestLap are shown in Table 5.2. By looking at thesevalues we can notice a small increase in the overall complexity of BestLap implementation.This is reflected in a increase in the vocabulary size, due to the addition of nine newclasses, and also a increase of 294 in the total LOC , which represent a 2.84% increase overthe total LOC of the conditional compilation version. We can also notice a small increasein NOO metric for some classes. This was caused by some refactorings required to extractArena feature. LCOO is also affected in some classes, since this metric depends on thecorrelation between operations, reflected by the set of common attributes they access,and, as part of the extraction of Arena feature, we have created new operations andmoved some attributes and operations to subclasses. Although this extraction implied in aslightly more complex implementation of BestLap, some of the artifacts that were affectedby the existence of Arena feature became less complex. One example is MainScreen classwhich had a 731 reduction in the LOC metric when the parts of the source code relatedto Arena were extracted to MainScreenArena subclass.

Java inheritance mechanism, which supports only single inheritance, was able to han-dle Arena extractions without problems. However, single inheritance is not able to handlecomposition of features at the class level in a scalable way, as it is not possible to definea class that is a compositions of two or more classes (by inheriting code and behaviorfrom these classes). Implementing compositions of features with single inheritance canlead to problems like code replication and exponential increase in the number of classes.Although we have not dealt with compositions of features in our experiments, we decidedto implement Arena feature with CaesarJ’s mixin-based inheritance mechanism in orderto observe how the use of this technology could impact on our results.

CeasarJ allows mixin composition in a special type called cclass, which are very similarto Java classes. Java classes and CaesarJ’s cclasses can coexist in a same projet, butthey can not be in the inheritance tree. That is, Java classes are not allowed to extendCaesarJ’s cclasses nor CaesarJ’s cclasses are allowed to extend Java classes. In orderto implement Arena feature to with CaesarJ’s mixin-based inheritance, we had to madesome adaptations to the version of BestLap implemented with Java inheritance. ForGameScreen, MainScreen and GameMenu classes and their respective subclasses, thetransition was very simple. We just changed the type of each class or subclass from Javaclass to CaesarJ’s cclass2. As cclasses are allowed to define any structure possible to aJava’s class, this modification was very easy.

1Some additional refactorings were also necessary.2We also had to convert Screen class to CaesarJ’s cclass type, since it is the superclass of MainScreen

class.

Page 104: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

82 EVALUATION

Class(Inheritance) LOC NOA NOO WOC LCOO CBC NCCLevelManager 615 46 22 33 183 10 2MainCanvas 609 68 30 54 329 27 8

MIDletController 105 7 14 15 67 11 1Resources 1470 277 45 109 990 27 9SESiemens 94 17 6 10 15 12 1

SoundEffects 313 20 12 20 4 17 11GameScreen 2505 244 59 93 1127 16 7MainScreen 610 40 22 42 127 12 4GameMenu 1255 141 28 37 242 11 5

NetworkFacade 409 28 13 21 60 22 27ArrayList 118 3 10 17 0 4 1

Screen 701 18 43 119 901 15 1BVGAnimator 364 23 13 30 66 12 1

Sprite 144 24 12 18 52 8 1BytePNG 187 10 15 30 103 7 1

BestlapFactory 20 0 6 6 15 7 2ArenaFactory 30 0 5 5 10 11 1

NoArenaFactory 25 0 5 5 10 6 1GameMenuArena 143 5 9 11 28 7 1GameScreenArena 11 0 1 1 0 2 1MainCanvasArena 15 0 1 2 0 2 1MainScreenArena 760 24 18 43 119 14 9

MIDletControllerArena 21 0 1 1 0 3 1ResourcesArena 115 32 6 8 15 8 1

Table 5.2 Metrics for BestLap SPL where Arena feature is implemented using Java’s inheri-tance mechanism.

The transition of MIDletController and MainCanvas classes and their respective sub-classes to CaesarJ’s cclasses was not straightforward, though. MIDletController extendsfrom MIDlet class, which represents a J2ME application. This class is the main classfor a J2ME application and is required to exist in any application developed for thisarchitecture. Also MainCanvas class is a subclass of Canvas3, which is a base classfor writing applications that need to handle low-level events and to issue graphics callsfor drawing to the display [5]. It was not possible to simple transform these classes inCaesarJ’s cclasses since they are part of the J2ME’s specification and are embedded inmobile devices that implement this specification. We solved this problem by using dele-gation. Two new classes were defined: BestlapMIDlet and MainCanvasDelegator, whichextend from Canvas and MIDlet classes respectively. They override some methods fromtheir superclasses and delegate them to MIDletController and MainCanvas cclasses. This

3Depending on which graphics API is used, it can also be a subclass of GameCanvas or FullCanvasclasses, which are also subclasses of Canvas class.

Page 105: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

EVALUATION 83

workaround increased the vocabulary size of BestLap by 2 and also the total LOC by 112.The metrics for the BestLap’s version where Arena feature is implement using CaesarJ’smixin-based inheritance are shown in Table 5.3.

Classe(Mixins) LOC NOA NOO WOC LCOO CBC NCCLevelManager 615 46 22 33 183 10 2MainCanvas 596 69 30 54 329 25 7

MIDletController 105 7 14 15 67 11 1Resources 1470 277 45 109 990 28 9SESiemens 94 17 6 10 15 12 1

SoundEffects 313 20 12 20 4 17 11GameScreen 2505 244 59 93 1127 16 7MainScreen 610 40 22 42 127 12 4GameMenu 1255 141 28 37 242 11 5

NetworkFacade 409 28 13 21 60 26 27ArrayList 118 3 10 17 0 4 1

Screen 701 18 43 119 901 15 1BVGAnimator 364 23 13 30 66 12 1

Sprite 144 24 12 18 52 8 1BytePNG 187 10 15 30 103 7 1

BestlapFactory 21 0 6 7 15 8 2ArenaFactory 31 0 5 6 10 11 1

NoArenaFactory 26 0 5 6 10 7 1GameMenuArena 143 5 9 11 28 7 1GameScreenArena 11 0 1 1 0 2 1MainCanvasArena 19 0 1 2 0 2 1MainScreenArena 760 24 18 43 119 15 9

MIDletControllerArena 22 0 1 1 0 4 1ResourcesArena 115 32 6 8 15 8 1

MainCanvasDelegator 93 1 20 33 190 6 3BestlapMIDlet 24 2 4 5 6 4 1

Table 5.3 Metrics for BestLap SPL where Arena feature is implemented using CaesarJ’s mixin-based inheritance mechanism.

The last step in our experiment was to implement Arena feature using AOP re-sources provided by AspectJ language. We have defined an aspect, ArenaAspect, whichis responsible for implementing Arena feature. ArenaAspect affects MainCanvas, MI-DletController, GameScreen, MainScreen, GameMenu, and Resources classes. We alsohad to define an aspect that is present in BestLap’s instances where Arena feature is notselected: NoArenaAspect. This extra aspect was necessary because have used AspectJ’sinter-type declaration mechanism to implement alternative initialization values for someconstants of GameMenu class, by placing the declaration of these constants in alternativeaspects. NoArenaAspect aspect can be seen as a part of the architecture of BestLap. It

Page 106: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

84 EVALUATION

is used to complement BestLap’s structure when arena feature is not selected. Thus,we do not consider NoArenaAspect aspect as part of the implementation of Arena fea-ture. The metrics for the version of BestLap where Arena feature is implemented usingAOP mechanisms provided by AspectJ language is shown in Table 5.4. As we have usedAspectJ’s inter-type declaration mechanism to extract the definition of methods and at-tributes from some classes to ArenaAspect, the values for NOA and NOO metrics forthese classes have reduced. This is reflected in high values for NOA and NOO metricsin ArenaAspect aspect. Table 5.5 shows NOEDA and NOEDO metrics for each class inwhich ArenaAspect aspect introduces some attribute or operation.

Class(AOP) LOC NOA NOO WOC LCOO CBC NCCLevelManager 615 46 22 33 183 10 2MainCanvas 608 60 30 54 329 26 8

MIDletController 104 7 14 15 67 10 1Resources 1470 277 45 109 990 27 9SESiemens 94 17 6 10 15 12 1

SoundEffects 313 20 12 20 4 17 11GameScreen 2505 244 59 93 1127 16 7MainScreen 610 40 22 42 127 12 4GameMenu 1212 141 25 34 164 12 5

NetworkFacade 409 28 13 21 60 26 27ArrayList 118 3 10 17 0 4 1

Screen 701 18 43 119 901 15 1BVGAnimator 364 23 13 30 66 12 1

Sprite 144 24 12 18 52 8 1BytePNG 187 10 15 30 103 7 1

NoArenaAspect 36 3 0 0 0 2 1ArenaAspect 1020 64 33 74 392 17 9

Table 5.4 Metrics for BestLap SPL where Arena feature is implemented using AOP technique.

Class(AOP) NOEDA NOEDOResources 32 6

MainScreen 24 15GameMenu 8 0

Table 5.5 NOEDA and NOEDO metrics for BestLap SPL where Arena feature is implementedusing AOP technique.

Table 5 shows a comparison of VS and total LOC metrics for each of the four BestLap’sversions. It also shows the values of CLOC, CDC and DoS metrics for Arena feature ineach of the four versions. By looking at these values, we can conclude that implementationof Arena using AOP resulted in a less impact on the complexity of BestLap SPL thanthe implementations that use single or mixin-based inheritance. It only resulted in a

Page 107: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

EVALUATION 85

more complex implementation when compared to the version where Arena feature isimplemented with conditional compilation technique.

Conditional compilation technique, however, provides no modularity for Arena featureat all. In this version, all the lines of source code related to Arena feature are tangled withother concerns of BestLap, defined between preprocessor directives. For the same reason,we consider that inheritance and mixins versions performed better in concern modularitythan conditional compilation version, although the conditional compilation version showsbetter values for CDC and DoS metrics. In fact, in the conditional compilation versionthe part of the code related to Arena feature is less scattered than in the inheritance ormixins versions, since it is found less entities. However, as we stated before, there is nonotion of concern modularity. In both inheritance and mixins versions (and also in AOPversion), we have defined components whose the only purpose is to implement Arenafeature. So, in this versions, it becomes much easier to reason about or to maintain thesource code related to this feature.

From the four versions, we consider the AOP version as the one that performed betterin separation of concerns. In this version, we have only two entities that implement Arenafeature: NetworkFacade class and ArenaAspect aspect. Both exist for the only purpose ofimplementing Arena feature. Also, the value for DoS metric is the best of all four versions.The value for this metric (0.434128) may appear high, as we know that CDC metric forArena feature in AOP version is only 2. This happens because DoS metric measures howmuch the code related to a concern is equally spread among the implementation artifacts.In AOP version, the part of the source code related to Arena feature is distributed asfollows: 71.38% in ArenaAspect aspect and 28.62% in NetworkFacade class. If the sourcecode lines related to Arena feature were more concentred in one of these entities (95%in ArenaAspect aspect and 5% in NetworkFacade class, for instance), the value for DoSmetric would be lower.

Cond. Compilation Inheritance Mixins AOPLOC 10348 10639 10751 10510

CLOCArena 1321 1508 1514 1429CDCArena 7 9 9 2

VS 15 24 26 17DoSArena 0.623702 0.685449 0.685878 0.434128

Table 5.6 Complexity and scattering metrics for Arena feature for the four versions of ourcase study.

So far, we have focused in metrics for the implementation assets of BestLap for eachof the four version considered in our experiment. Now, we discuss the impact of theseapproaches to implement Arena feature in the resulting bytecode size (BS metric) ofBestLap’s instances.

Table 5.7 shows the values of BS metric for our case study. As expected, the versionwhere Arena feature was implemented with conditional compilation, resulted in the lowestvalues for BS metric. An interesting conclusion comes when we compare the third columnwith the fifth. The version of BestLap where Arena feature is implemented using AOP

Page 108: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

86 EVALUATION

Bytecode syze (bytes)Instance Cond. Compilation Inheritance Mixins AOPMOT1 72.712 76.914 79.809 75.105MOT2 85.148 89.326 92.224 87.540MOT3 72.742 76.924 79.833 75.122

S40 65.129 69.339 72.259 67.542S40M2 72.793 77.028 79.892 75.197

S40M2V3 72.327 76.517 79.405 74.722S60M1 85.380 89.583 92.513 87.791S60M2 84.304 88.488 91.345 86.708SAM1 66.406 67.218 69.328 66.608SAM2 80.414 81.230 83.297 80.607SE01 70.984 75.157 78.192 73.364SE02 84.158 88.339 91.231 86.537SE03 72.386 76.587 79.469 74.781SE04 72.335 76.539 79.426 74.743

SIEM2 72.389 76.590 79.379 74.770SIEM3 73.068 77.277 80.076 75.460SIEM4 72.303 76.512 79.310 74.686

Mean 74.999 78.798 81.588 77.134

Table 5.7 Bytecode Size metric values for Arena feature experiments.

patterns outperform the implementation using inheritance patterns in this criterion. Thesizes from the second, third and fifth columns were obtained after compiling the BestLapsource code with the ABC compiler. The values of the fourth column where obtainedafter the use of the CaesarJ compiler. The use of this compiler was necessary to supportmixins. The use of CaesarJ compiler to support mixins resulted in an extra overhead. Infact, the version using mixins obtained the worst results. From the instances of BestLapshown in the table, only SAM1 and SAM2 do not include Arena feature, even though,a small impact can be seen in BS metric for this instances. This impact is due to theadditional infrastructure added to the architecture of BestLap in order to implementArena feature in a modular way. However, the impact is indeed much lower than theimpact observed in other instances.

5.1 APPLICABILITY OF PATTERNS

The implementations of this case study were guided by the variation types and patternsintroduced in Chapter 4. Four different variation types were identified. In some cases,we have a direct occurrence of a variation type in the source code. Sometimes, though,it is necessary to refactor the source code in order to create an occurrence of a knownvariation type and, thus, to open an opportunity to the our set of patterns. Table 5.1shows a summary of which variation types were identified and how many occurrencesof each variation type we found during the implementation of Arena optional feature.

Page 109: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

5.1 APPLICABILITY OF PATTERNS 87

For every variation type found, we applied one of the patterns proposed to handle thatvariation type.

Direct After RefactoringVariation in Class Attribute 64 0

Variation in the Whole Body of a Method 21 4Variation in the Beginning or End of Method Body 1 2

Variation in Structure Around Method Body 0 5

Table 5.8 Bytecode Size metric values for Arena feature experiments

Almost all the refactorings we applied during the experiments where guided by thecatalog of variation types. We aimed to find variabilities in source that matched our setof known variation types. Only one refactoring was not directly related to any pattern:a refactoring in the persistence mechanism of BestLap. To easy the implementation ofArena feature in a modular fashion, we decided to split the game’s record store4 (originallyone) in two: one specific for persisting data related to Arena feature and another to persistall other data. This refactoring not only was not guided by our catalog of variation types,but also required knowledge of the application domain.

Although the set of variation catalog and the set of patterns are useful to guide theimplementation of variabilities in SPLs, they are not complete in the sense that can beused to implement any variability. Also, as we have verified, knowledge of the applicationdomain can help the developer in the task of modularizing variabilities.

Also, there was no necessity to refactor ArenaAspect in order to explore AspectJ’squantification mechanism. This was due to the fact that Arena is a heterogeneous cross-cutting concern. For a homogeneous crosscutting concern there would be opportunitiesfor refactorings in the aspect, which would avoid code replication. We regard the imple-mentation of a homogeneous crosscutting concern using the approach described in thisthesis as a future work.

4A record store consists of a collection of records which will remain persistent across multiple invo-cations of a MIDlet. Record stores are part of the J2ME’s Record Management System [5].

Page 110: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram
Page 111: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

CHAPTER 6

CONCLUDING REMARKS

In this work, we have presented a set of evaluation criteria and metrics for assessingquality attributes of software product lines. This framework of evaluation was used tocompare variability implementation techniques. In order to compare these techniques,we had first defined groups of variation types. For each variation type, we offer a setof implementation patterns. Each pattern use one or more techniques to implement avariability.

What defines a variation type is the location in the source code where they appearand which structure of the program is varying. This information the relevant when aprogrammer is applying transformations in the source code of an existing program inorder to deal with a new variability. For each point of the program where a variation isto be introduced, the programmer first identify which variation type matches the specificsituation1 and then chooses, among a set of patterns, one variability implementationpattern to deal with this situation. Our approach indeed helps the creation and evolutionof SPLs using the extractive and reactive adoption strategies.

Once identified a variation type to be implemented, the developer has in hands aportfolio of implementation patterns and needs to choose one. To help this decision wehave implemented situations where these patterns are applied and then compared theresulting versions against the following criteria: complexity of source code, modularity,separation of concerns, and efficiency in bytecode generation. We have used some metricsin order to generate quantitative data to be based upon when comparing the patterns.This way, our model provides useful information for the programmer to choose the bestpattern to apply, given a current context and priorities. Another characteristic of ourpatterns is that they are not just a recommendation of a technique. Instead, they describehow a technique can be used to implement a specific variation type. We also include sourcecode examples.

Finally, we have evaluated the use of our model in a case study consisting in theimplementation of a crosscutting optional feature of an industrial mobile game. We haveverified the efficacy of composite applications of our patterns, and how the existence ofour variation types catalog can guide the implementation of variabilities in a SPL.

The catalog of variation types has been created by the examination of the sourcecode of games for mobile devices. However, we also identified that some variation typesfrom our catalog also appears in the domain of automated test cases [25, 24]. We expect,although we can not guarantee, that our results are valid for other applications domains,as well.

1If no match in the catalog of variation types is found, the programmer may need to refactor thesource code first.

89

Page 112: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

90 CONCLUDING REMARKS

6.1 CONTRIBUTIONS

The contributions of the this work are the following:

� The definition of criteria to compare the implementations of SPLs and a set ofmetrics to evaluate SPLs against each criteria (we have proposed four new metricsto this purpose);

� A discussion of guidelines to apply software metrics in a SPL context;

� A catalog of variation types, based on the location of the variation in the sourcecode (which aims to help the embrace of extractive and reactive SPL adoptionstrategies);

� A set of variability implementation patterns for each variation type of the catalog;

� A comparison of the performance of the set of patterns (according to differentcriteria) for each variation type;

� An evaluation of our model (variation types catalog and set of patterns) to imple-ment a crosscutting variability in an industrial SPL.

6.2 RELATED WORK

In [12] it is considered the problem of choosing techniques for implementing artifacts forSPLs. According to this work, little attention had been given on how to deal with SPLsat the implementation level. The author presents some techniques that can be used toaccomplish this task and compares them using some qualitative criteria. Properties likescalability, traceability and separation of concerns are considered. No case study withquantitative data is presented in this work.

The problem of handling variabilities at the source code level is also explored in [53].Some techniques are presented and evaluated in terms of which type of variability theysupport (optional, alternative, or-features, positive and negative). The following tech-niques are considered: conditional compilation, polymorphism, refinements, and AOP.After a brief discussion and analysis of each technique, a small case study is considered:a component to perform automated tests. No quantitative data is collected in order tocompare the performance of each technique.

In [59] some variability enabling techniques are discussed, as well as their advantagesand drawbacks. The following criteria are used to compare the techniques: scope, flexi-bility, efficiency, ease of introduction, separation of concerns, scalability, traceability, andtool support. It is discussed how each technique can perform in relation to these crite-ria. The work does not provided any source code examples and also do not show anyquantitative evaluation.

A method for addressing the creation and evolution of SPLs focusing at the imple-mentation and feature model level is presented in [10]. The method first bootstraps theSPL and then evolves it with a reactive approach. The method also relies on a collection

Page 113: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

6.3 OPEN ISSUES AND FUTURE WORK 91

of provided refactorings at the feature and implementation level. Although some othervariability enabling techniques are discussed, the method focus in AOP.

A recent work [24] focus on the implementation of variabilities in automated testcases. The work presents a decision model to help developers on the task of choosingmechanisms to restructure test variabilities in SPLs. The decision model and the mech-anisms suggested by this study can result in an improvement in the modularity of thetests variabilities and also the remove of some bad smells such as cloned code.

In [23] it is proposed a method called Multi-Paradigm Design. This method consistsof analyzing commonalities and variabilities of a SPL (application domain analysis) andimplementation techniques (solution domain analysis). Further, the commonalities andvariabilities are mapped on the available techniques (solution domain). Our approachdiffers from his work because we rely on a set of implementation patterns that are code-centric and more fine-grained than the domain analysis solution that he proposes, allowingSPL developers to choose more easily which technique to use when handling variabilitiesat the source code level.

6.3 OPEN ISSUES AND FUTURE WORK

We have evaluated our catalog of variation types and patterns in a single mobile gameSPL: BestLap. An interesting future work would be to repeat these experiments in otherapplications from the same domain, and also in applications from different domains, inorder to gain confidence that the results presented in this thesis can be generalized. Wealso think that, the analysis of other applications and domains may lead to an expansionin the catalog of types of variations and patterns, as new variation types may be foundand also new requirements might demand the creation of new patterns.

Our work was also restricted to some techniques that are among the most used toimplement variabilities. Indeed the consideration of other techniques would enrich thecurrent results. Exploration of additional techniques would also expand the set of patternsfor each variation type, giving more opportunities to developers. In addition to newtechniques, new tools should be considered for evaluation. For example, the analysis ofthe impact of a given technique over the resulting application size truly depends on whichcompilers, obfuscators and other optimizations tools are used.

Another very important future work is the investigation of criteria and approaches toevaluate SPLs. In Chapter 3, we have discussed and problem of evaluating SPLs and alsoproposed new metrics and evaluation guidelines. However, more research in this topic isbe necessary. Also, research and development of tools to support evaluation of SPLs is ahigh demanding issue.

Finally, it is necessary to work towards a formal definition of each variability im-plementation pattern. In the context of a SPL developed with the reactive adoptionapproach, the use of a pattern can be seen as a program transformation that offers op-portunity to variability. These programs transformations can be formally defined in termsof pre and post conditions. Such a formal definition, not only increases the confidencethat the use of a pattern would not break an existing program, but also is necessary forthe development of a tool that provides automation to the model proposed in this thesis.

Page 114: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram
Page 115: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

BIBLIOGRAPHY

[1] CaesarJ Project, 2007. Last visit: July, 2007.

[2] Antenna: An ant-to-end solution for wireless java, 2008. Last visit: March, 2008.

[3] Apache Ant, 2008. Last visit: March, 2008.

[4] Captain Feature, 2008. Last visit: March, 2008.

[5] J2ME Mobile Information Device Profile API, 2008. Last visit: March, 2008.

[6] JavaTM 2 platform standard edition 5.0 API specification, 2008. Last visit: March,2008.

[7] SableCC Project, 2008. Last visit: March, 2008.

[8] J. Aldrich. Open modules: A proposal for modular reasoning in aspect-orientedprogramming. In Foundations of Aspect Languages, March 2004.

[9] Vander Alves. Identifying variations in mobile devices. 4(3):47–52, April 2005.

[10] Vander Alves. Implementing Software Product Line Adoption Strategies. PhD thesis,Federal University of Pernambuco, Brazil, 2007.

[11] Vander Alves, Ivan Cardim, Heitor Vital, Pedro Sampaio, Alexandre Damasceno,Paulo Borba, and Geber Ramalho. Comparative analysis of porting strategies inj2me games. In Proceedings of the 21st IEEE International Conference on SoftwareMaintenance (ICSM’05), pages 123–132. ACM Press, September 2005.

[12] Michalis Anastasopoulos and Cristina Gacek. Implementing Product Line Variabili-ties. In Proceedings of the 2001 Symposium on Software Reusability (SSR’01), pages109–117, New York, NY, USA, 2001. ACM Press.

[13] Sven Apel, Thomas Leich, Marko Rosenmuller, and Gunter Saake. Combiningfeature-oriented and aspect-oriented programming to support software evolution.In In AMSE’05, at ECOOP’05, 2005.

[14] Ivica Aracic, Vaidas Gasiunas, Mira Mezini, and Klaus Ostermann. An overview ofcaesarj. 3880:135–173, 2006.

93

Page 116: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

94 BIBLIOGRAPHY

[15] Pavel Avgustinov, Aske Simon Christensen, Laurie Hendren, Sascha Kuzins, JenniferLhotak, Ondrej Lhotak, Oege de Moor, Damien Sereni, Ganesh Sittampalam, andJulian Tibble. abc: an extensible AspectJ compiler. In Proceedings of the 4thInternational Conference on Aspect-Oriented Software Development (AOSD 2005),pages 87–98. ACM Press, 2005.

[16] Alexandre Bergel, Robert Hirschfeld, Siobhan Clarke, and Pascal Costanza. As-pectboxes – controlling the visibility of aspects. In Proceedings of the InternationalConference on Software and Data Technologies (ICSOFT 2006), 2006.

[17] Paulo Borba, Fernando Calheiros, Vilmar Nepomuceno, Andrea Menezes, SergioSoares, , and Vander Alves. Flip - product line derivation tool. In Forum Demonstra-tion at Seventh International Conference on Aspect-Oriented Software Development,AOSD.08, Brussels, Belgium, 2008. ACM.

[18] Gilad Bracha. The Programming Language Jigsaw: Mixins, Modularity and MultipleInheritance. PhD thesis, 1992.

[19] Tarcisio Camara, Rodrigo Lima, Rangner Guimaraes, Alexandre Damasceno, VanderAlves, Pedro Macedo, and Geber Ramalho. Porting games in j2me: Challenges, casestudy, and guidelines (in portuguese). In Scientia, volume 16, pages 66–72, 2005.

[20] Tarcisio Camara, Rodrigo Lima, Rangner Guimaraes, Alexandre Damasceno, Van-der Alves, Pedro Macedo, and Geber Ramalho. Massive mobile games porting:Meantime study case. In In Brazilian Symposium on Computer Games and DigitalEntertainment - Computing track, 2006.

[21] P. Clements and L. Northrop. Software Product Lines: Practices and Patterns.Addison-Wesley, 2001.

[22] Leonardo Cole and Paulo Borba. Deriving refactorings for aspectj. In AOSD ’05:Proceedings of the 4th international conference on Aspect-oriented software develop-ment, pages 123–134, New York, NY, USA, 2005. ACM.

[23] James Coplien. Multi-Paradigm Design. PhD thesis, Vrije Universiteit Brussel,Etterbeek, Belgium, July 2000.

[24] Marcio de Medeiros Ribeiro. Restructuring test variabilities in software productlines, 2008.

[25] Marcio de Medeiros Ribeiro, Pedro Matos Jr., Paulo Borba, and Ivan Cardim. Onthe Modularity of Aspect-Oriented and Other Techniques for Implementing ProductLines Variabilities. In Proceedings of the 1st Latin American Workshop on Aspect-Oriented Software Development (LA-WASP’07), in conjunction with the 21th Brazil-ian Symposium on Software Engineering (SBES’07), pages 119–130, October 2007.

[26] Edsger Dijkstra. Notes on structured programming. Structured Programming, 1968.

Page 117: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

BIBLIOGRAPHY 95

[27] Marc Eaddy, Alfred Aho, and Gail C. Murphy. Identifying, assigning, and quanti-fying crosscutting concerns. In ICSEW ’07: Proceedings of the 29th InternationalConference on Software Engineering Workshops, page 162, Washington, DC, USA,2007. IEEE Computer Society.

[28] Eduardo Figueiredo, Nelio Cacho, Claudio Sant’Anna, Mario Monteiro, UiraKulesza, Alessandro Garcia, Sergio Soares, Fabiano Ferrari, Safoora Khan, Fer-nando Castor Filho, and Francisco Dantas. Evolving software product lines withaspects: an empirical study on design stability. In ICSE ’08: Proceedings of the 30thinternational conference on Software engineering, pages 261–270, New York, NY,USA, 2008. ACM.

[29] Eduardo Figueiredo, Carlos Lucena, and Alessandro Garcia. Uma abordagem quan-titativa para desenvolvimento de software orientado a aspectos. Proceedings of the6th Brazilian Simposium on Software Quality, pages 501–515, 2007. In portuguese.

[30] Robert E. Filman and Daniel P. Friedman. Aspect-oriented programming is quan-tification and obliviousness. Technical report, 2000.

[31] Martin Fowler. Refactoring: Improving the Design of Existing Code. Addison-WesleyProfessional, June 1999.

[32] Martin Fowler. UML Distilled: A Brief Guide to the Standard Object ModelingLanguage. Addison-Wesley Longman Publishing Co., Inc., Boston, MA, USA, 2003.

[33] Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides. Design Patterns.Addison-Wesley, January 1995.

[34] William G. Griswold, Kevin Sullivan, Yuanyuan Song, Macneil Shonle, NishitTewari, Yuanfang Cai, and Hridesh Rajan. Modular Software Design with Crosscut-ting Interfaces. IEEE Software, 23(1):51–60, 2006.

[35] Jilles Van Gurp, Jan Bosch, and Mikael Svahnberg. On the notion of variabilityin software product lines. In WICSA ’01: Proceedings of the Working IEEE/IFIPConference on Software Architecture, page 45, Washington, DC, USA, 2001. IEEEComputer Society.

[36] Software Engineering Institute. Software Product Lines. World Wide Web, http://www.sei.cmu.edu/productlines/, 2008.

[37] Stan Jarzabek and Li Shubiao. Eliminating redundancies with a ”composition withadaptation” meta-programming technique. In Proceedings of the 9th European soft-ware engineering conference held jointly with 11th ACM SIGSOFT internationalsymposium on Foundations of software engineering, pages 237–240. ACM Press,2003.

Page 118: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

96 BIBLIOGRAPHY

[38] Pedro Matos Jr, Rafael Duarte, Ivan Cardim, and Paulo Borba. Using design struc-ture matrices to assess modularity in aspect-oriented software product lines. InProceedings of 1st Workshop on Assessment of Contemporary Modularization Tech-niques (ACoM’07), in conjunction with the 29th International Conference on Soft-ware Engineering (ICSE’07), page 4, Washington, DC, USA, 2007. IEEE ComputerSociety.

[39] Kyo Kang, Sholom Cohen, James Hess, William Novak, and Spencer Peterson.Feature-oriented domain analysis (FODA) feasibility study. Technical ReportCMU/SEI-90-TR-21, Software Engineering Institute, Carnegie Mellon University,November 1990.

[40] Gregor Kiczales, John Lamping, Anurag Mendhekar, Chris Maeda, Cristina Lopes,Jean-Marc Loingtier, and John Irwin. Aspect–Oriented Programming. In Proceed-ings of European Conference on Object–Oriented Programming (ECOOP’97), LNCS1241, pages 220–242. Addison-Wesley, June 1997.

[41] Gregor Kiczales and Mira Mezini. Aspect-Oriented Programming and Modular Rea-soning. In Proceedings of the 27th International Conference on Software Engineering(ICSE 2005), pages 49–58. ACM Press, 2005.

[42] Charles Krueger. Easing the transition to software mass customization. In Proceed-ings of the 4th International Workshop on Software Product–Family Engineering,pages 282–293, October 2001.

[43] Charles W. Krueger. Variation management for software production lines. In SPLC2: Proceedings of the Second International Conference on Software Product Lines,pages 37–48, London, UK, 2002. Springer-Verlag.

[44] Ramnivas Laddad. AspectJ in Action: Practical Aspect-Oriented Programming.Manning Publications Co., Greenwich, CT, USA, 2003.

[45] Ramnivas Laddad. Aspect Oriented Refactoring. Addison-Wesley Professional, 2006.

[46] Barbara Liskov. Keynote address - data abstraction and hierarchy. SIGPLAN Not.,23(5):17–34, 1988.

[47] Fernando Lopes. Otimizando compiladores de AspectJ para Java ME. Final workrequired to obtain the bachelor’s degree in Computer Science at Federal Universityof Pernambuco, 2007. In portuguese.

[48] J.D. McGregor, S. Jarrad, L.M. Northrop, and K. Pohl. Initiating software productlines. IEEE Software, 19(4):24–27, 2002.

[49] M. D. McIlroy. Mass produced software components. Proc. Nato Software Engineer-ing Conference, pages 138–155, 1968.

Page 119: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

BIBLIOGRAPHY 97

[50] Alberto Costa Neto, Marcio de Medeiros Ribeiro, Marcos Dosea, Rodrigo Bonifacio,Paulo Borba, and Sergio Soares. Semantic Dependencies and Modularity of Aspect-Oriented Software. In Proceedings of 1st Workshop on Assessment of ContemporaryModularization Techniques (ACoM’07), in conjunction with the 29th InternationalConference on Software Engineering (ICSE’07), page 11. IEEE Computer Society,2007.

[51] Federal University of Pernambuco. JaTS - Java Transformation System, 2001. Lastvisit: March, 2008.

[52] David L. Parnas. On the design and development of program families. IEEE Trans-actions on Software Engineering, 2(1):1–9, 1976.

[53] Thomas Patzke and Dirk Muthig. Product Line Implementation Technologies. Tech-nical Report 057.02/E, Fraunhofer Institut Experimentelles Software Engineering,October 2002.

[54] Klaus Pohl, Gunter Bockle, and Frank J. van der Linden. Software Product LineEngineering: Foundations, Principles and Techniques. Springer, 2005.

[55] Claudio Sant`Anna, Alessandro Garcia, Christina Chavez, Carlos Lucena, and Arndtvon Staa. On the reuse and maintenance of aspect-oriented software: An assessmentframework. Proceedings of Brazilian Symposium on Software Engineering, pages19–34, 2003.

[56] Thiago Santos and Andre Santos. Parameterizing java software. In ProceedingsSBLP‘05 IX Brazilian Symposium on Programming Languages, pages 257–270, 2005.

[57] Alan Snyder. Encapsulation and inheritance in object-oriented programming lan-guages. In Norman Meyrowitz, editor, Proceedings of the Conference on Object-Oriented Programming Systems, Languages, and Applications (OOPSLA), vol-ume 21, pages 38–45, New York, NY, 1986. ACM Press.

[58] Kevin Sullivan, William G. Griswold, Yuanyuan Song, Yuanfang Cai, MacneilShonle, Nishit Tewari, and Hridesh Rajan. Information Hiding Interfaces for Aspect-Oriented Design. In Proceedings of the 10th European Software Engineering Confer-ence held jointly with 13th ACM SIGSOFT International Symposium on Foundationsof Software Engineering (ESEC/FSE), pages 166–175, New York, NY, USA, 2005.ACM Press.

[59] Antti Tirila. Variability Enabling Techniques for Software Product Lines. Master’sthesis, Tampere University of Technology, Tampere, Finland, September 2002.

Page 120: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram
Page 121: ANALISYS OF TECHNIQUES FOR ... - twiki.cin.ufpe.br · ACKNOWLEDGEMENTS Agrade˘co, em primeiro lugar, a meus pais, por todo o apoio que me deram desde que nasci. Eles que sempre estiveram

This volume has been typeset in LATEXwith the UFPEThesis class (www.cin.ufpe.br/∼paguso/ufpethesis).


Recommended