Energy Efficiency Analysis of Code Refactoring Techniques ...

17
electronics Article Energy Efficiency Analysis of Code Refactoring Techniques for Green and Sustainable Software in Portable Devices ˙ Ibrahim ¸ Sanlıalp 1, * , Muhammed Maruf Öztürk 2 and Tuncay Yi˘ git 2 Citation: ¸ Sanlıalp, ˙ I.; Öztürk, M.M.; Yi ˘ git, T. Energy Efficiency Analysis of Code Refactoring Techniques for Green and Sustainable Software in Portable Devices. Electronics 2022, 11, 442. https://doi.org/10.3390/ electronics11030442 Academic Editor: Claus Pahl Received: 20 November 2021 Accepted: 27 January 2022 Published: 1 February 2022 Publisher’s Note: MDPI stays neutral with regard to jurisdictional claims in published maps and institutional affil- iations. Copyright: © 2022 by the authors. Licensee MDPI, Basel, Switzerland. This article is an open access article distributed under the terms and conditions of the Creative Commons Attribution (CC BY) license (https:// creativecommons.org/licenses/by/ 4.0/). 1 Graduate School of Natural and Applied Sciences, Suleyman Demirel University, Isparta 32260, Turkey 2 Department of Computer Engineering, Faculty of Engineering, Suleyman Demirel University, Isparta 32260, Turkey; [email protected] (M.M.Ö.); [email protected] (T.Y.) * Correspondence: [email protected] Abstract: Code refactoring is a time-consuming and effort-intensive process that is applied for making improvements to source codes. There exist several refactoring techniques to improve software quality. Some of them aim to reduce the energy consumption of the software. However, the combination of applied refactoring techniques is crucial to the success rate. In addition, to provide sustainable services on portable devices such as mobile phones and laptops, which rely on batteries, improving and optimizing the energy efficiency is important. This study focuses on examining the effect of code refactoring techniques on energy consumption. A total of 25 different source codes of applications programmed in the C# and Java languages are selected for the study, and combinations obtained from refactoring techniques are applied to these source codes. The combinations applied are analyzed using the maintainability index. Power consumption estimation tools are used to measure the energy consumption of the original and refactored codes. The results show that the combinations significantly improve the software’s energy efficiency. The results will provide a better understanding of the relationship between the energy efficiency of software and refactoring techniques. Moreover, they will help developers to improve their object-oriented code in terms of both energy efficiency and sustainability. Keywords: code refactoring; energy consumption; green and sustainable software; energy efficiency; object-oriented code; maintainability index; sustainability 1. Introduction Today, energy consumption and dependence on energy are issues that concern all countries worldwide [1]. Alongside the increase in the global population, the use of information and communication technologies is also increasing. In order to maintain the continuity of these technologies, both hardware and software infrastructures are used and energy consumption increases greatly as a result of increased use [2]. Every action made to develop software has a cost and it results in an increase in the carbon emission. The approach that its practitioners call green software engineering [3] is an emerging paradigm that aims to develop green-enabled software to reduce negative impacts on the environment. The software solutions developed are based on observing innovations in the software development process followed and the refactoring technique used without disturbing the code’s function. With the advent of electronic devices such as smartphones, tablets, and laptops, reducing energy consumption has become an important issue for researchers [4]. Further, the usage time of portable devices has increased significantly in parallel. As the use of these devices becomes more widespread, the applications developed to meet different user needs become larger and more complex. One way to reduce the energy consumption of portable devices is to improve the software quality [5]. Code refactoring is a possible method to address this problem because it supports the restructuring of existing source codes to obtain more energy-efficient code. Electronics 2022, 11, 442. https://doi.org/10.3390/electronics11030442 https://www.mdpi.com/journal/electronics

Transcript of Energy Efficiency Analysis of Code Refactoring Techniques ...

electronics

Article

Energy Efficiency Analysis of Code Refactoring Techniquesfor Green and Sustainable Software in Portable Devices

Ibrahim Sanlıalp 1,* , Muhammed Maruf Öztürk 2 and Tuncay Yigit 2

�����������������

Citation: Sanlıalp, I.; Öztürk, M.M.;

Yigit, T. Energy Efficiency Analysis of

Code Refactoring Techniques for

Green and Sustainable Software in

Portable Devices. Electronics 2022, 11,

442. https://doi.org/10.3390/

electronics11030442

Academic Editor: Claus Pahl

Received: 20 November 2021

Accepted: 27 January 2022

Published: 1 February 2022

Publisher’s Note: MDPI stays neutral

with regard to jurisdictional claims in

published maps and institutional affil-

iations.

Copyright: © 2022 by the authors.

Licensee MDPI, Basel, Switzerland.

This article is an open access article

distributed under the terms and

conditions of the Creative Commons

Attribution (CC BY) license (https://

creativecommons.org/licenses/by/

4.0/).

1 Graduate School of Natural and Applied Sciences, Suleyman Demirel University, Isparta 32260, Turkey2 Department of Computer Engineering, Faculty of Engineering, Suleyman Demirel University,

Isparta 32260, Turkey; [email protected] (M.M.Ö.); [email protected] (T.Y.)* Correspondence: [email protected]

Abstract: Code refactoring is a time-consuming and effort-intensive process that is applied for makingimprovements to source codes. There exist several refactoring techniques to improve software quality.Some of them aim to reduce the energy consumption of the software. However, the combinationof applied refactoring techniques is crucial to the success rate. In addition, to provide sustainableservices on portable devices such as mobile phones and laptops, which rely on batteries, improvingand optimizing the energy efficiency is important. This study focuses on examining the effect of coderefactoring techniques on energy consumption. A total of 25 different source codes of applicationsprogrammed in the C# and Java languages are selected for the study, and combinations obtained fromrefactoring techniques are applied to these source codes. The combinations applied are analyzedusing the maintainability index. Power consumption estimation tools are used to measure theenergy consumption of the original and refactored codes. The results show that the combinationssignificantly improve the software’s energy efficiency. The results will provide a better understandingof the relationship between the energy efficiency of software and refactoring techniques. Moreover,they will help developers to improve their object-oriented code in terms of both energy efficiencyand sustainability.

Keywords: code refactoring; energy consumption; green and sustainable software; energy efficiency;object-oriented code; maintainability index; sustainability

1. Introduction

Today, energy consumption and dependence on energy are issues that concern allcountries worldwide [1]. Alongside the increase in the global population, the use ofinformation and communication technologies is also increasing. In order to maintain thecontinuity of these technologies, both hardware and software infrastructures are usedand energy consumption increases greatly as a result of increased use [2]. Every actionmade to develop software has a cost and it results in an increase in the carbon emission.The approach that its practitioners call green software engineering [3] is an emergingparadigm that aims to develop green-enabled software to reduce negative impacts on theenvironment. The software solutions developed are based on observing innovations inthe software development process followed and the refactoring technique used withoutdisturbing the code’s function.

With the advent of electronic devices such as smartphones, tablets, and laptops,reducing energy consumption has become an important issue for researchers [4]. Further,the usage time of portable devices has increased significantly in parallel. As the use ofthese devices becomes more widespread, the applications developed to meet differentuser needs become larger and more complex. One way to reduce the energy consumptionof portable devices is to improve the software quality [5]. Code refactoring is a possiblemethod to address this problem because it supports the restructuring of existing sourcecodes to obtain more energy-efficient code.

Electronics 2022, 11, 442. https://doi.org/10.3390/electronics11030442 https://www.mdpi.com/journal/electronics

Electronics 2022, 11, 442 2 of 17

Considering the frequency of the need for energy in portable devices allows a bet-ter understanding of the importance of refactoring techniques in energy consumption.Object-oriented languages are common among developers, in accordance with the needfor contemporary coding. Therefore, this study investigates object-oriented projects todetermine the efficacy of refactoring techniques.

Specific studies giving advice for reducing energy consumption according to thecode structure and software development model are available in the literature. Despitethis popularity, refactoring techniques that vary and evolve dramatically are examinedindividually in only a few works. Arguably, it is of great significance for developers to knowthe change in energy consumption depending on the selected refactoring technique [6]. Inthe studies that address energy consumption, some studies examine energy consumptionaccording to the selected software development model [7] (for instance, data managementtechniques in developing software). Furthermore, it has been found that the refactoringeffectiveness is not consistent because of the difference in applications [8]. Moreover,one of the most remarkable studies that explains the effects of refactoring on energyconsumption is Kim et al.’s work [9]. Some double combinations of refactoring techniquesare involved in their experiment in terms of energy consumption. It is clearly seen that thestudy reducing energy consumption up to 2.4% was performed with codes retrieved fromone programming language. The study demonstrated that the interaction of refactoringtechniques should be investigated comprehensively. Moreover, yet another directionis to learn how the refactoring techniques should be combined. However, the binarycombination of refactoring techniques is only investigated on embedded systems.

To the best of our knowledge, there is no comprehensive work analyzing the interac-tion of only triple combinations of refactoring techniques in terms of energy consumption.Further, preceding works are generally focused on a specific problem rather than present-ing an overview. On the other hand, evaluating refactoring techniques individually doesnot give beneficial advice about energy consumption to practitioners. On the contrary,using refactoring techniques without considering the effects of their combinations on thesource code could be misleading in interpreting energy consumption. The current studydescribes the most detailed experiment with regard to the number of refactoring techniquesin the combinations. In this study, the effects of the use of five different refactoring tech-niques and their triple combinations on energy consumption are investigated with twosoftware applications including 25 source files. The experiment performed in this papercomprises code-level modifications. In the study, we use software metrics and comparedmeasurements from software estimation tools to find the optimal combination of softwarequality and energy. The findings will help developers to improve their object-oriented codefor both energy efficiency and sustainability. The remainder of the study is organized asfollows: the second section contains a summary of related studies. The third section coversthe materials and methods of the experimental work. In the fourth section, the results ofthe study are given. The fifth section details the threats to the validity of the study. Thefinal section discusses the conclusions and future directions. Figure 1 shows a summary ofthis paper.

Electronics 2022, 11, 442 3 of 17

Definition of theresearch aim and

objectives

Review of relatedstudies

Determination ofused refactoring

techniques

Selection ofdataset

Analysis of combination list of

the refactoringtechniques

Experimentalthreats to validity,conclusions and

researchrecommendations

Findings,discussion and

results

Estimation ofenergy

consumption

Figure 1. Summary flowchart for the structure of the paper.

2. Related Studies

Green software should consist of effective, low-resource-consuming, and, in partic-ular, profitable codes in terms of energy consumption, because one way to reduce theenergy consumption of electronic devices such as smartphones, tablets, and laptops is toimprove the software quality [5]. Refactoring the code is one possible way to address thisissue. Green software studies with code refactoring techniques, which can be consideredtrailblazers, have become more prevalent in the literature in the last decade [10,11].

Pioneering studies on the relationship between code refactoring techniques and soft-ware energy efficiency were conducted by Silva et al. [12] and Gottschalk et al. [13].Silva et al. [12] investigated the change in energy consumption values after the "InlineMethod", which is one of the most widely used refactoring techniques, was applied to twodifferent embedded systems. It was observed that refactoring techniques had a positiveeffect on energy consumption, especially in mobile devices with an Android operatingsystem. Gottschalk et al. [13] optimized the energy-wasteful code detected in the sourcecodes of mobile device applications by refactoring techniques. They also saw energy con-sumption as a major issue for Android devices and suggested an approach to reduce theenergy consumption of applications by reengineering processes, including code refactoring.

One of the most comprehensive studies investigating the effects of refactoring tech-niques in energy consumption was performed by Sahin et al. [8]. They used six coderefactorings provided by the Eclipse IDE to 9 Java programs and analyzed their energyconsumption. According to their findings, refactoring techniques lead to either an increaseor decrease in energy consumption. Since every application has special characteristics, thiscase seems to be not consistent. Park et al. [6] measured the energy consumption values ofC++ codes based on 63 different refactoring techniques. In this measurement, 33 techniqueswere identified as energy-efficient techniques. In the study, the energy consumption valuesin the combination of techniques were not considered in relation to the interaction.

Experiments in subsequent studies have shown that refactoring techniques have apositive effect on energy consumption in mobile devices, especially those using the Androidoperating system [14]. Morales et al. [15] proposed a model validation approach calledEARMO. This approach proposes refactoring techniques that can reduce energy consumption.

Kim et al. [9] carried out a study examining the energy consumption values byapplying more than one refactoring technique together. This study is one of the mostremarkable studies explaining the effects of refactoring techniques on energy consumption.Binary combinations with seven different refactoring techniques were tested on embeddedsystem codes. However, binary combinations were produced based on similarity. Sehgalet al. [16] investigated how refactoring plays an important role in reducing power usage.This study revealed that applying appropriate refactoring techniques reduces batteryconsumption. As a result, it was emphasized that improving the code with the refactoringtechnique is a good step towards energy efficiency.

Electronics 2022, 11, 442 4 of 17

Recently, in addition to existing studies, researchers have focused on choosing theorder of refactoring techniques that helps to achieve optimum software sustainability[17,18], eliminating applications with a bad smell in mobile applications using refactoringtechniques; there have also been studies on the effect of code on energy optimization [19].

The studies listed above have some limitations, which are as follows: (1) existingstudies have addressed energy consumption as an energy-saving problem; (2) they have notdealt with energy consumption in detail in terms of the interaction of refactoring techniques;(3) using refactoring techniques without considering the effects of their combinations on thesource code could be misleading when interpreting energy consumption rates. The mainmotivation of this study is to fill this gap by applying triple combinations of refactoringtechniques on source codes for mobile phones and laptops.

3. Materials and Methods

This section provides energy consumption estimations, including a detailed demon-stration of the conceptual framework of the experimental work, applied refactoring tech-niques, data collection, analysis of combinations, and hardware configuration.

Figure 2 shows the conceptual framework of the present study. The general aim ofthe study is to investigate combinations of code refactoring techniques in terms of energyefficiency in open-source object-oriented software applications.

Original Codes

Refactored Codes

Estimate Energy C

onsumption

ApplyRefactoringTechniques

5 Refactoring Techniques

Data Objects Source Codes Combination Listof Refactoring

Techniques

IntelPower Gadget

Trepn Profiler

2 Applications

Calculate Metric Value

Analyze and Apply

Combinations

Com

pare Energy Consum

ption

IntelPower Gadget

Trepn Profiler

EnergyConsumptionof Refactored

Codes

EnergyConsumption

of OriginalCodes

Figure 2. Conceptual framework.

First, source codes written in Java and C# and the refactoring techniques to be appliedwere selected. Second, a triple combination list was prepared from the selected refactoringtechniques. According to our knowledge, there is not any comprehensive study to datethat analyzes the interaction of triple combinations of refactoring techniques in terms ofenergy consumption. In addition to this, energy usage can be reduced if the techniquesare used for multiple different parts of a source code [9]. Third, after constructing allthe combinations of refactoring techniques, they were integrated into the source codesto be applied. Next, the triple combination list was analyzed using the software metricmaintainability index [20]. Thus, it was detected which combinations were to be employedby regarding the change in metric value. Then, detected combinations were integratedinto the source codes to be applied. After this, energy consumption estimates were made

Electronics 2022, 11, 442 5 of 17

for the source codes, which were then be called the “refactored codes” and the “originalcodes”. Finally, a general evaluation of the original and refactored codes was conducted.

3.1. Refactoring Techniques

Code refactoring is a disciplined technique for improving software quality by alteringthe internal structure of code without changing its external behavior. Although somebasic operations including refactoring techniques are offered in the development tools,the main purpose of which is to improve the readability, performance, and maintenanceof the code, special methods can also be developed. Software developers, engineers,or researchers want to use more stable refactoring techniques to maintain open-sourcesoftware development [6].

Refactoring techniques can be performed manually or automatically by developers. Theycan also be applied depending on the coding type and can be applied to many computerprograms in the software industry. Many refactoring techniques can be used to obtain moreenergy-efficient code. In addition, refactoring techniques consider energy efficiency as a factorin software quality [6]. However, while some of them make a positive contribution to energyconsumption, others negatively affect energy consumption [9]. Positive refers to reducingenergy consumption, while negative refers to increasing energy consumption.

To examine the source codes in terms of energy efficiency, five refactoring techniques [4,6,9,21], known to contribute positively to energy efficiency, were selected for the study sincethey have a high frequency of practical use, as shown in a literature review [22], and areeasy to implement in C# and Java. In addition, the selected techniques significantly reducethe number of lines of code or complexity of the applications, so the contribution of thesetechniques to energy efficiency in applications is intriguing. Details of these are given in Table1. At the same time, Table 2 illustrates motivating examples of the refactoring techniques usedin the study.

Table 1. Refactoring techniques.

Notation Name Description

R1 Encapsulate field Makes a public field private;Creates getter and setter methods [6].

R2 Inline temp Replaces variable references with itself [4].

R3 Introduce explaining variable Adds variables in the code where there is a complex expression tomake the expression simpler [6].

R4 Simplify nested loop Converts the nested loop structure into a single loop [9].

R5 Replace delegation with inheritance Replaces the delegate with inheritance [21].

3.1.1. Encapsulate Field

Encapsulation is one of the refactoring techniques that alleviates the software mainte-nance process. The main purpose of this refactoring technique is to set access permissionsof a variable. If there is any performance concern, encapsulation may generate an adverseeffect. This means that using getters and setters may invoke additional function calls. Thus,it may lead an application to perform less well [23]. However, this technique is generally agood design practice that allows the encapsulation of the fields of a class and might havean impact on energy efficiency [6]. Get and set functions are configured by selecting aspecific field.

Electronics 2022, 11, 442 6 of 17

Table 2. Motivating examples.

Notation Code Example of Refactoring Technique

R1

Name Examples

public static int matrixSign public static int matrixSign (int row, int column){ (int row, int column){ Simplify Nested Loop public int iterations=100; public int iterations=100; public int result=0; public int result=0; for(int i = 0; i <row ; i++){ for(int i = 0; i < row*column*iteration; i++)

for(int j = 0; j <column; j++){ { result+ = row*column; } for(int k = 0; k <iterations; k++{ return result; result+=row*column; } }

} } return result; } When the operation of the inner loop consists of several simple operations, it is combined into a single loop.

Inline Temp var result = MessageBox.Show(message, caption, if (MessageBox.Show(message, caption, MessageBoxButtons.OKCancel, MessageBoxButtons.OKCancel,

MessageBoxIcon.Question); MessageBoxIcon.Question) ==DialogResult.OK) if (result == DialogResult.OK)

If there is a temporary variable in the code block that assigns the result of an expression

and no more, this variable can be replaced with the expression itself.

public class Game public class Game

{ { Encapsulate Field public int length; private int length;

} public int length {

get { return length; } set { length = value ; } } }

If it is necessary to hide the object data of the code from other classes or objects,

it is hidden with access specifiers.

Introduce Explaining if (i < csvRow.Length - 1 && csvRow[i] == quoteChar && csvRow[i + 1] == quoteChar)

Variable

bool active = i < csvRow.Length - 1 && csvRow[i] == quoteChar && csvRow[i + 1] == quoteChar;

if (active)

If there is a complex expression in the code, it puts it in a temporary variable with a name that describes

the purpose.

public class Game{ public class Game {

public int Score(){ public int Score(){

… …

} }

Replace Delegation public class NewGame(){ public class NewGame : Game

with Inheritance private Game Game {get; set;} {

public NewGame(){ …

Game = new Game() }

}

public int Score(){

return Game.Score();

}

}

Replaces a delegation relationship between two classes with an inheritance relationship. This eliminates

the need for delegation methods and reduces code size.

R2

Name Examples

public static int matrixSign public static int matrixSign (int row, int column){ (int row, int column){ Simplify Nested Loop public int iterations=100; public int iterations=100; public int result=0; public int result=0; for(int i = 0; i <row ; i++){ for(int i = 0; i < row*column*iteration; i++)

for(int j = 0; j <column; j++){ { result+ = row*column; } for(int k = 0; k <iterations; k++{ return result; result+=row*column; } }

} } return result; } When the operation of the inner loop consists of several simple operations, it is combined into a single loop.

Inline Temp var result = MessageBox.Show(message, caption, if (MessageBox.Show(message, caption, MessageBoxButtons.OKCancel, MessageBoxButtons.OKCancel,

MessageBoxIcon.Question); MessageBoxIcon.Question) ==DialogResult.OK) if (result == DialogResult.OK)

If there is a temporary variable in the code block that assigns the result of an expression

and no more, this variable can be replaced with the expression itself.

public class Game public class Game

{ { Encapsulate Field public int length; private int length;

} public int length {

get { return length; } set { length = value ; } } }

If it is necessary to hide the object data of the code from other classes or objects,

it is hidden with access specifiers.

Introduce Explaining if (i < csvRow.Length - 1 && csvRow[i] == quoteChar && csvRow[i + 1] == quoteChar)

Variable

bool active = i < csvRow.Length - 1 && csvRow[i] == quoteChar && csvRow[i + 1] == quoteChar;

if (active)

If there is a complex expression in the code, it puts it in a temporary variable with a name that describes

the purpose.

public class Game{ public class Game {

public int Score(){ public int Score(){

… …

} }

Replace Delegation public class NewGame(){ public class NewGame : Game

with Inheritance private Game Game {get; set;} {

public NewGame(){ …

Game = new Game() }

}

public int Score(){

return Game.Score();

}

}

Replaces a delegation relationship between two classes with an inheritance relationship. This eliminates

the need for delegation methods and reduces code size.

R3

Name Examples

public static int matrixSign public static int matrixSign (int row, int column){ (int row, int column){ Simplify Nested Loop public int iterations=100; public int iterations=100; public int result=0; public int result=0; for(int i = 0; i <row ; i++){ for(int i = 0; i < row*column*iteration; i++)

for(int j = 0; j <column; j++){ { result+ = row*column; } for(int k = 0; k <iterations; k++{ return result; result+=row*column; } }

} } return result; } When the operation of the inner loop consists of several simple operations, it is combined into a single loop.

Inline Temp var result = MessageBox.Show(message, caption, if (MessageBox.Show(message, caption, MessageBoxButtons.OKCancel, MessageBoxButtons.OKCancel,

MessageBoxIcon.Question); MessageBoxIcon.Question) ==DialogResult.OK) if (result == DialogResult.OK)

If there is a temporary variable in the code block that assigns the result of an expression

and no more, this variable can be replaced with the expression itself.

public class Game public class Game

{ { Encapsulate Field public int length; private int length;

} public int length {

get { return length; } set { length = value ; } } }

If it is necessary to hide the object data of the code from other classes or objects,

it is hidden with access specifiers.

Introduce Explaining if (i < csvRow.Length - 1 && csvRow[i] == quoteChar && csvRow[i + 1] == quoteChar)

Variable

bool active = i < csvRow.Length - 1 && csvRow[i] == quoteChar && csvRow[i + 1] == quoteChar;

if (active)

If there is a complex expression in the code, it puts it in a temporary variable with a name that describes

the purpose.

public class Game{ public class Game {

public int Score(){ public int Score(){

… …

} }

Replace Delegation public class NewGame(){ public class NewGame : Game

with Inheritance private Game Game {get; set;} {

public NewGame(){ …

Game = new Game() }

}

public int Score(){

return Game.Score();

}

}

Replaces a delegation relationship between two classes with an inheritance relationship. This eliminates

the need for delegation methods and reduces code size.

R4

Name Examples

public static int matrixSign public static int matrixSign (int row, int column){ (int row, int column){ Simplify Nested Loop public int iterations=100; public int iterations=100; public int result=0; public int result=0; for(int i = 0; i <row ; i++){ for(int i = 0; i < row*column*iteration; i++)

for(int j = 0; j <column; j++){ { result+ = row*column; } for(int k = 0; k <iterations; k++{ return result; result+=row*column; } }

} } return result; } When the operation of the inner loop consists of several simple operations, it is combined into a single loop.

Inline Temp var result = MessageBox.Show(message, caption, if (MessageBox.Show(message, caption, MessageBoxButtons.OKCancel, MessageBoxButtons.OKCancel,

MessageBoxIcon.Question); MessageBoxIcon.Question) ==DialogResult.OK) if (result == DialogResult.OK)

If there is a temporary variable in the code block that assigns the result of an expression

and no more, this variable can be replaced with the expression itself.

public class Game public class Game

{ { Encapsulate Field public int length; private int length;

} public int length {

get { return length; } set { length = value ; } } }

If it is necessary to hide the object data of the code from other classes or objects,

it is hidden with access specifiers.

Introduce Explaining if (i < csvRow.Length - 1 && csvRow[i] == quoteChar && csvRow[i + 1] == quoteChar)

Variable

bool active = i < csvRow.Length - 1 && csvRow[i] == quoteChar && csvRow[i + 1] == quoteChar;

if (active)

If there is a complex expression in the code, it puts it in a temporary variable with a name that describes

the purpose.

public class Game{ public class Game {

public int Score(){ public int Score(){

… …

} }

Replace Delegation public class NewGame(){ public class NewGame : Game

with Inheritance private Game Game {get; set;} {

public NewGame(){ …

Game = new Game() }

}

public int Score(){

return Game.Score();

}

}

Replaces a delegation relationship between two classes with an inheritance relationship. This eliminates

the need for delegation methods and reduces code size.

R5

Name Examples

public static int matrixSign public static int matrixSign (int row, int column){ (int row, int column){ Simplify Nested Loop public int iterations=100; public int iterations=100; public int result=0; public int result=0; for(int i = 0; i <row ; i++){ for(int i = 0; i < row*column*iteration; i++)

for(int j = 0; j <column; j++){ { result+ = row*column; } for(int k = 0; k <iterations; k++{ return result; result+=row*column; } }

} } return result; } When the operation of the inner loop consists of several simple operations, it is combined into a single loop.

Inline Temp var result = MessageBox.Show(message, caption, if (MessageBox.Show(message, caption, MessageBoxButtons.OKCancel, MessageBoxButtons.OKCancel,

MessageBoxIcon.Question); MessageBoxIcon.Question) ==DialogResult.OK) if (result == DialogResult.OK)

If there is a temporary variable in the code block that assigns the result of an expression

and no more, this variable can be replaced with the expression itself.

public class Game public class Game

{ { Encapsulate Field public int length; private int length;

} public int length {

get { return length; } set { length = value ; } } }

If it is necessary to hide the object data of the code from other classes or objects,

it is hidden with access specifiers.

Introduce Explaining if (i < csvRow.Length - 1 && csvRow[i] == quoteChar && csvRow[i + 1] == quoteChar)

Variable

bool active = i < csvRow.Length - 1 && csvRow[i] == quoteChar && csvRow[i + 1] == quoteChar;

if (active)

If there is a complex expression in the code, it puts it in a temporary variable with a name that describes

the purpose.

public class Game{ public class Game {

public int Score(){ public int Score(){

… …

} }

Replace Delegation public class NewGame(){ public class NewGame : Game

with Inheritance private Game Game {get; set;} {

public NewGame(){ …

Game = new Game() }

}

public int Score(){

return Game.Score();

}

}

Replaces a delegation relationship between two classes with an inheritance relationship. This eliminates

the need for delegation methods and reduces code size. 3.1.2. Inline Temp

The problem emerging with assigning a result to a temporary variable before ex-pressing it is generally addressed with the extract method. Instead, inline temp obtainsresults by invoking the value returned by the function. This is one of the processes thatincreases the readability of a program. Note that, while applying inline temp, it shouldbe controlled whether the value returned by the function is to be used for an extensiveoperation. If an extensive operation is needed, the inline temp can be considered moreviable. In addition, eliminating temporary variables speeds up the fetching of redundanttemporary variables from both the main and cache memories [4]. This approach improvesperformance and maintains the same level of energy efficiency, which is considered apositive improvement [4,6].

Electronics 2022, 11, 442 7 of 17

3.1.3. Introduce Explaining Variable

Low-level simplification of complex expressions and conditional expressions is amongthe characteristics of refactoring types. One of them, the introduce explaining variable, is alow-level code-based refactoring technique that simplifies a complex expression [24]. If itdetects a complex expression within the technical code, it puts the result of the expressionor parts of the expression in a temporary variable with a name describing the purpose [25].Thus, the complex expression is simplified by introducing new variables into the code.

3.1.4. Simplify Nested Loop

If a loop has a double or more dimensional structure, this loop should be simplified.This simplification is possible by reducing the dimensions of the loop. For instance, ifthree-dimensional structures are reduced to two-dimensional, this is a suitable refactor-ing operation. Dimension reduction of multi-dimensional loops helps to reduce energyconsumption. Moreover, numerous loops can be simplified, making the code even morereadable and energy-efficient [9].

3.1.5. Replace Delegation with Inheritance

Inheritance is used to share functionality between two classes [21]. Delegation allowsthe dynamic changing of the delegate, which cannot be done with a superclass in mostobject-oriented programming languages. If one replaces delegation with inheritance, itmakes the class a delegate inheriter by purging the delegate method. It also eliminates theneed to create a delegation method for each new delegate class method. Thus, the numberof lines of code can be reduced.

3.2. Data Collection

Since games on portable devices are energy-intensive applications [26], game-basedbuilt-in applications that have existed for some years and have an active user communitywere determined as the primary criteria in the dataset selection of our study. Anothercriterion is that the applications must be compatible with at least three refactoring tech-niques since it is possible to reduce the energy consumption if the techniques are appliedto several different sections within a source code [9]. Finally, an attempt is made to analyzeplain codes, which would allow the desired changes and contain object relations. Thestudy focuses on Java and C# applications for object-oriented programming and covers thefindings of these languages. They are frequently used as they are the most compatible withthe tools analyzed for the maintainability of the software [27] and are preferred in energyefficiency studies [28,29]. These two languages have similar syntax, and applications withcommon goals written in these two languages show similar characteristics in terms ofclass encapsulation, polymorphism, and reusability [30]. However, it is not known exactlywhether they show similarity in terms of energy efficiency.

Game 2048 is a single-player numbers game and is played on a 4 × 4 grid. The aimof the game is to reach the number 2048 by combining the numbers in the 16 squareson the screen with each other. The 2048 applications are game-based. The 2048 desktopapplication is a Windows Form-based application coded in C#. The 2048 mobile applicationis an Android application coded in Java. These applications are small open-source appsavailable on Github, with an average of around 1000 lines of code. They include classencapsulation, inheritance, mathematical operations, global variables, local variables, andloop structures. In addition, basic control structures of sequence and iteration are detectedin terms of source code.

Open-source code is preferred in applications in order to be able to access the sourcecode and to test applications written in Java on an Android device. The source codes of theapplications used in the study were arranged to apply the selected refactoring techniques,and the edited versions are expressed as the original source code in the rest of the article.In addition, the application of refactoring techniques individually and in combination wasperformed manually in this study. Before applying the agreed refactoring techniques, the

Electronics 2022, 11, 442 8 of 17

size and complexity of the experimental applications were measured. To extract the staticcode metrics of these applications, LocMetrics [31] was used. This tool is used to countLines of Code (LOC), Physical Line of Code (SLOC-P), Logical Line of Code (SLOC-L), andMcCabe’s Cyclomatic Complexity (CC).

1. LOC is found by counting all source code, including blank lines, comment lines, anddead codes [32]. Code lines can be defined as SLOC-P and SLOC-L.

2. SLOC-P is calculated by subtracting the total number of blank lines and commentlines from the number of source code lines [33].

3. SLOC-L is calculated by counting the program statements that are likely to be exe-cuted [34].

4. CC tries to measure the complexity of the related program using the control flowgraph [35].

These metrics are the oldest and most widely used size measurements [36,37]. LOCand CC can affect energy consumption and software quality [38]. As the dimension of CCincreases, it becomes extremely difficult to test a software program [39]. The obtained valuesof the original source codes of the experimental applications are given in Table 3. This tableindicates that the mobile application of 2048 has more files than the desktop application of2048. Moreover, the LOC, SLOC-P, and SLOC-L of the 2048 desktop application code aresmaller than the 2048 mobile application code. According to the value of CC in the table,the mobile application’s code complexity is greater.

Table 3. Summary of experimental applications.

Name FileNumber LOC SLOC-P SLOC-L CC

2048 (desktop application) 1 8 806 578 353 922048 (mobile application) 2 17 1204 938 698 132

1 https://github.com/retecata/2048-in-Csharp (accessed on 12.09.2021); 2 https://github.com/roxrook/2048-android (accessed on 9 December 2021); LOC: lines of code; SLOC-P: physical executable source lines of code;SLOC-L: logical executable source lines of code; CC: McCabe’s cyclomatic complexity.

3.3. Analysis of Combination List

Ten different combination lists were obtained from the triple combinations of refactor-ing techniques. The combination list is represented by CL = (C1, C2, ...., Ci) , and i consistsof integer variables, where i is the number of combinations. The resulting list is shown inTable 4. While ”X” denotes the selection of the refactoring technique for combination, therefactoring techniques having the ” − ” label were eliminated.

Table 4. Representation of all possible combinations of applied techniques.

Notation C1 C2 C3 C4 C5 C6 C7 C8 C9 C10

R1 X X X - - - X X X -R2 X - - X X - X X - XR3 X X - X X X - - X -R4 - X X X - X X - - XR5 - - X - X X - X X X

C1: Combination of R1,R2,R3; C2: Combination of R1,R3,R4; C3: Combination of R1,R4,R5; C4: Combinationof R2,R3,R4; C5: Combination of R2,R3,R5; C6: Combination of R3,R4,R5; C7: Combination of R1,R2,R4; C8:Combination of R1,R2,R5; C9: Combination of R1,R3,R5; C10: Combination of R2,R4,R5.

The list was analyzed with the maintainability index metric value. The aim wasto check whether the combinations of maintainability measurement values contributedpositively to the energy consumption values. The maintainability index (MI) is a softwaremeasure that measures how maintainable (supporting and modifying) the source code is.The MI formula consists of a combination of CC and Halstead Volume (HV) [40]. Thismetric has an important place among software metrics as it provides information about the

Electronics 2022, 11, 442 9 of 17

complexity, maintenance, and maintainability of the code. MI is calculated by Equation (1)[20]:

MI = 171 − 5.2 × ln(HV)− 0.23 × (CC)− 16.2 × ln(LOC) (1)

According to Coleman, an MI value above 85 indicates that the software is highlymaintainable, a value between 85 and 65 indicates moderate maintainability, and a valuebelow 65 indicates that the system is difficult to maintain and has low maintainability[20]. The MI was calculated using the Code Metrics [33] and JHawk [41] tools for the2048 desktop applications coded in C# and the 2048 mobile applications coded in Java,respectively.

3.4. Energy Consumption Estimation

Energy consumption was estimated for the source codes written in C# and Javaprogramming languages. Other object-oriented programming languages were not withinthe scope of this study. Two open-source applications were measured.

To estimate the energy consumption, two software power estimators named IntelPower Gadget [42] and Trepn Profiler [43] were used. They both support object-orientedcode-based estimation. The Intel Power Gadget tool includes elapsed time, packet powerlimit, processor frequency, graphics processing unit frequency, processor temperature,average, and total power of the processor. The Trepn Profiler samples data every 100milliseconds and presents them in different data visualization modes. It allows real-timeraw data transfer for offline analysis [44]. The tools used save the results as a CSV file. Theenergy unit is converted by the Intel Power Gadget by calculating with Equation (2) [45]for the Trepn Profiler:

Energy(Joule) = (power

106 )W × (pro f ilingtime

103 )s (2)

Watts (W) are used to measure power, while joules (J) are used to measure the cu-mulative watt-seconds (W-s) required to perform the work [46,47]. The experiments run10 tests per original and refactored code because the results after over 10 runs aimed toreduce the impact of cold starts and cache effects [48] so that possible noise or outliersin the results could be reduced. Test measurements were carried out in periods of 300 s.When the tests are all the same length, the average watt (average power) is commonlyused [46,47]. During the measurements, the energy consumption values consumed by theprograms in consecutive time intervals tend to differ. Therefore, it was very important forthis study to determine the average power consumption per second in each programminglanguage. Thus, the average was considered significant in the current study and the en-ergy consumed in joules during a test was calculated by multiplying the average wattsby the seconds. Energy consumption values were recorded for both laptop and mobilephone devices. The Intel Power Gadget was used to save the laptop’s values. The TrepnProfiler was chosen to record the energy footprint of the Android-based Java application.The desktop app experiments were performed offline on a laptop with Windows 10 Pro[49] as an operating system. The laptop device had the following configurations: IntelCore i7-8750H , 2.20 GHz, 8 GB RAM, and 256 GB disk space. The Android-based Javaproject was tested on a Samsung Galaxy J7 Prime running Android 8.1. The device wasequipped with an octa-core, 1.6 GHz Cortex-A53 Qualcomm Snapdragon 617 processor ,3 GB system memory, and 16 GB storage. Power profiles containing cumulative energyconsumption values were saved as .csv files, which were then analyzed offline accordingto the recommended method. For the laptop, measurements were taken in both idle andairplane mode. The devices that provided external communication, such as Wi-Fi andBluetooth, were set to be offline. Network power was not taken into account as all theexperiments were performed offline. In addition, the laptop and mobile phone experimentswere performed at the same time interval (5 min) [23,50]. Energy consumption depends onexecution time and power, as shown in Equation (2). In this study, the execution time was

Electronics 2022, 11, 442 10 of 17

kept constant and the common time was determined for both platforms. The minimumrecommended time for Android tools was used for the laptop measurements. Thus, thesame time interval was used to obtain comparisons based on reliable results. Moreover, theminimum number of applications required for the experiment (OS core services, energymetering tool, metered application, etc.) was allowed in concurrent execution and eachexperiment was performed with 100% battery. The same configuration was also applied tothe mobile phone to produce a reliable evaluation.

4. Results

The Wilcoxon signed-rank statistical test [51], which is a type of non-parametric test,was used to determine whether the difference between the amount of energy consumedby the original code and refactored code of each applications was statistically significant.The Wilcoxon signed-rank test was run at a significance level of 0.05 to judge energyconsumption before refactoring and after refactoring. This test was chosen since it hasno bias about the data distribution for both applications. In hypothesis zero (H0), thedistribution in the energy consumption results of the refactored code was the same as thedistribution in the energy consumption results of the original code. Conversely, if therewas a significant difference between the distribution of energy consumption results of therefactored code and the distribution of energy consumption results of the original code,the hypothesis was one (H1). If the p value was less than 0.05, the distribution of energyconsumption results of the refactored codes differed significantly from the distribution ofenergy consumption results of the original code. The results of the test given in Table 5show that the distribution was different for the original and refactored code. It can be seenthat the p values of the original and refactored code were less than 0.05. Therefore, werejected H0, which was the opposite of the significant difference among the test objectives.

Table 5. Results of Wilcoxon signed-rank test for the original and refactored codes (H0:p > 0.05,H1:p < 0.05).

R1 R2 R3 R4 R5 C1 C3 C4

ine 2048 a (p value) 0.007 0.005 0.011 0.005 0.022 0.005 0.009 0.005ine 2048 b (p value) 0.031 0.028 0.028 0.018 0.043 0.022 0.018 0.025ine

a Original code of desktop application, b Original code of mobile application.

In the 2048 desktop application, there was a statistically significant difference (p ≤ 0.022)between the original and refactored codes. The differences between the original and refac-tored codes in the 2048 mobile application were also statistically significant (p ≤ 0.043).As a result, it is clearly seen from Table 5 that R1, R2, R3, R4, R5, C1, C3, and C4 achievedsignificantly different results to the original code of the applications.

As a result of the list analysis, combinations of refactoring techniques with optimummaintainability index values were selected. Table 6 shows the maintainability valuesextracted from the Code Metrics and JHawk tools for each of the selected combinations.While the MI value of the original source codes of the 2048 mobile application coded withJava was 66, the MI value of the original source codes of the 2048 desktop applicationcoded with C# was 115.63.

Electronics 2022, 11, 442 11 of 17

Table 6. The effect of the maintainability index on the combinations in the source code of theapplications and the percentage change rates of the combinations.

Name MI Org. C1 C2 C3 C4 C5 C6 C7 C8 C9 C10

2048 (desktop Value 66 70 68 71 70 69 67 67 68 68 67application) %change - +6.06 +3.03 +7.58 +6.06 +4.54 +1.52 +1.52 +3.03 +3.03 +1.52

2048 (mobile Value 115.63 121.00 117.96 122.10 121.90 116.00 119.62 119.96 116.57 115.95 118.74application) %change - +4.64 +2.02 +5.60 +5.42 +0.32 +3.45 +3.74 +0.81 +0.27 +2.69

Org.: Original,MI: Maintainability index.

Regarding the results from the maintainability measurements of the two applications,it is apparent from the values of the maintainability index that the MI of C3, which is acombination of R1, R4, and R5 , has the highest value among all other combinations for bothapplications. This means that C3 increased the maintenance effort of these applications. Thelowest maintainability index for the 2048 mobile application is C9, which is a combinationR1, R3, and R5. However, it achieved slightly higher results than the maintainabilityindex of the original codes of this application. This shows that C9 contributes slightly tothe maintenance effort of this application. Another important point is that the distinctivetechnique is R3 for C9, because this technique makes a difference in terms of maintainabilityon the interaction between techniques. According to Table 6, the values obtained from thetools show a significant increase in MI values for C1, C3, and C4 compared to the originalcodes in both applications. These were determined as the optimum combinations. Thedetails of the optimum combinations of the applications are given in Table 7.

Table 7. Demonstration of optimum combinations of 2048 desktop and mobile applications.

Notation C1 C3 C4

R1 X X -R2 X - XR3 X - XR4 - X XR5 - X -

Table 8, which includes the experimental results of the energy consumption analysis,reports the mean, median, and percentage change of energy consumption measurements.It also reports the standard deviation of the measurements.

Table 8. Results of energy consumption. All experiments were carried out at same time interval (300 s).

Energy Consumption (J) of 10 Runs (Median, Mean, S.D.)

Name Type Org. R1 R2 R3 R4 R5 C1 C3 C4

2048 (desktop Median 1465.65 1442.00 1435.50 1436.50 1414.75 1446.44 1406.00 1398.58 1391.45application) %change - −1.61 −2.06 −1.99 −3.47 −1.31 −4.07 −4.58 −5.06

Mean 1462.45 1440.46 1436.90 1432.36 1415.18 1446.65 1407.49 1399.83 1391.79%change - −1.50 −1.75 −2.06 −3.23 −1.08 −3.75 −4.28 −4.83S.D. 15.58 16.50 13.38 12.26 13.18 16.00 13.36 19.71 6.41

2048 (mobile Median 184.59 179.36 178.24 176.90 172.59 182.38 171.74 167.64 171.90application) %change - −2.83 −3.44 −4.17 −6.50 −1.19 −6.96 −9.18 −6.88

Mean 184.71 179.62 177.94 177.02 171.22 181.55 171.42 168.46 170.62%change - −3.03 −3.67 −4.70 −7.30 −1.71 −7.20 −9.33 −7.63S.D. 4.46 5.57 3.1 5.74 5.32 4.43 5.39 5.48 5.66

S.D.: Standard deviation.

The average energy consumption for the original code of the game in the 2048 desktopapplication was 1462.45 J, while the average energy consumption for the original code ofthe mobile application was measured as 184.71 J.

Electronics 2022, 11, 442 12 of 17

4.1. Assessing Energy Consumption of Each Refactoring Technique

Each refactoring technique has a special code-modifying behavior. To determine this,they should be examined individually. To reduce the impact of uncontrolled behavior andto control the possibility of reducing energy consumption, we first analyzed the originalcode and the impact of each refactoring technique on the source codes individually. Theenergy consumption of the applications was measured ten times before each refactoringtechnique was applied and ten times after each refactoring technique was applied. Theresults are shown in Figures 3 and 4.

2048 (desktop application)

En

erg

yC

on

sum

pti

on

(Jo

ule

)

Org.

R1 R2 R3 R4 R5

1360

1380

1400

1420

1440

1460

1480

1500

R1: Encapsulate field

R2: Inline temp

R3: Introduce explaining variable

R4: Simplify nested loop

R5: Replace delegation with inheritance

Org. : Original code values

Figure 3. Boxplot of energy consumption results of the original and refactored codes for the laptopdataset. The x axis represents the name of each dataset and the y axis represents the energy consumption.

2048 (mobile application)

En

erg

yC

on

sum

pti

on

(Jo

ule

)

Org.

R1R2 R3 R4 R5

140

150

160

170

180

190

200

R1: Encapsulate field

R2: Inline temp

R3: Introduce explaining variable

R4: Simplify nested loop

R5: Replace delegation with inheritance

Org. : Original code values

Figure 4. Boxplot of energy consumption results of the original and refactored codes for the mo-bile phone dataset. The x axis represents the name of each dataset and the y axis represents theenergy consumption.

As can be observed in Table 8, the energy reduction rate in using R4 seems quiteimpressive for both applications. When implementing R5, the probability of a positivecontribution to energy efficiency is lower, whereas, when performing R4, the probabilityof a contribution to energy efficiency is higher for the combinations, because the R5 savesthe smallest amount of energy in both applications. Results from the application of eachof the five refactoring techniques showed that all of the techniques could save energy.Among these, the R4 technique was the one that provided the best energy savings, as seenin Figures 3 and 4. The R5 technique provided the smallest energy savings in the 2048application. This is because, when applied to the original code of 2048, the reduction inmethod calls did not cause a significant reduction in byte code calls and consequentlyhad little impact on energy efficiency. The energy consumption of R2 for the 2048 mobileapplication is more consistent than the original codes as the interquartile range is smallerthan the original code values.

Although R1, R2, and R3 techniques differed between applications, they contributedpositively to energy efficiency for both applications.

Electronics 2022, 11, 442 13 of 17

4.2. Assessing Energy Consumption of Combinations

Figures 5 and 6 show the details of the cumulative energy consumption for codesrefactored by the original codes and combinations of the refactoring techniques. In order toevaluate the selected combinations in terms of energy consumption, Table 8, Figure 5, andFigure 6 were examined.

2048 (desktop application)E

ner

gy

Co

nsu

mp

tio

n(J

ou

le)

Org.

C1 C3 C4

1360

1380

1400

1420

1440

1460

1480

1500

C1: Combination of R1-R2-R3

C3: Combination of R1-R4-R5

C4: Combination of R2-R3-R4

Org. : Original code values

Figure 5. Boxplot of energy consumption results of original codes and combinations of refactoringtechniques for the laptop dataset. Each dataset was measured 10 times. The x axis represents thename of each dataset and the y axis represents the energy consumption.

2048 (mobile application)

En

erg

yC

on

sum

pti

on

(Jo

ule

)

Org.

C1C3 C4

140

150

160

170

180

190

200

C1: Combination of R1-R2-R3

C3: Combination of R1-R4-R5

C4: Combination of R2-R3-R4

Org. : Original code values

Figure 6. Boxplot of energy consumption results of original codes and combinations of refactoringtechniques for the mobile phone dataset. The x axis represents the name of each dataset and the yaxis represents the energy consumption.

The combination of the R1, R2, and R3 techniques showed that C1 reduced the energyconsumption for both applications. C1 affects the most costly blocks, cos(), sus(), stanga(),and drepta(), in the 2048 desktop application source code. In the 2048 mobile application,C1 affects the mergeLeft(), mergeRight(), mergeUp(), and mergeDown() methods in the Matrixclass. Each block has a separate energy cost. However, replacing complex expressions incode blocks with a variable reduced the energy significantly. C1 also allows variables to beallocated less space in memory and shortens the time to retrieve them from the cache. As aresult, the number of cycles during instruction execution is reduced, and this combinationreduces the energy consumption. Similarly, C3, which is a combination of R1, R4, andR5, tended to reduce the energy consumption of the applications. C3 affects, in the othermost costly blocks, processCmdKey(), which have loops, comparisons, method invocations,parameter passing, and boolean operations, in the 2048 desktop application. Game class,which is the source code of the desktop application, is affected by the R5 implementation.This class invokes the processCmdKey(). In the 2048 mobile application, onCreate() andonMove() are the code blocks that C3 affects more. After refactoring, loop structures andmethod invocations provided significant energy savings for both applications. However,

Electronics 2022, 11, 442 14 of 17

C3 achieved a lower energy consumption rate for the 2048 mobile application than the 2048desktop application. In this application, the interaction of refactoring techniques drawsattention as a result of the refactoring combination obtained by the R1, R4, and R5, becausethe deletion of temporary variables affected the number of iterations in the single loopstructure and provided a large amount of energy reduction. In the combination R1, R4,and R5, R4 is a distinctive technique in terms of energy consumption between applications.Moreover, the energy consumption ranges of C3 varied by several orders of magnitude,and the lower quartile of C3 for the 2048 mobile application was lower than the others.

C4, which is a combination of R2, R3, and R4, contributed positively to energy effi-ciency for both applications. C4 affects the blocks gameover(), newGameToolStripMenuItem-Click(), and processCmdKey() in the desktop application source code. In the Java source code,C4 affects mergeLeft(), mergeRight(), mergeUp(), mergeDown(), and matrix() code blocks. Thiscombination refactors array comparisons, assignments, and loop structure in both sourcecodes, which contributes the most to the cost. However, the percentage of change in energyconsumption for the 2048 mobile application of C4 was close to the percentage of changein energy consumption of the R4 technique applied to the code, which is associated withthe simplification of the loop structure. Moreover, the percent change in the energy con-sumption of C4 did not approximate the mathematical addition of the techniques’ percentchange in individual energy consumption [9]. Because the techniques, including C4, do notinteract with each other, it was observed that the change in the number of codes for the2048 mobile application was small and energy efficiency was less affected.

The results validate that the maintainability index, which indicates the maintainabilityof the code, is useful in choosing combinations of refactoring techniques for the energyconsumption of the 2048 application coded in C#. However, this does not apply to all theselected combinations of the 2048 application coded in Java. In summary, from the graphsin Figures 5 and 6, and Table 8, we can conclude that the refactoring technical combinationsgenerally positively affected energy consumption.

5. Threats to Validity

First, the scope of the experiment was limited to two types of programming languages.Second, manual refactoring is often error-prone and takes time. In this study, this processwas driven manually. Energy consumption thus varied depending on how the program-mers refactored the original code. Third, we tried to conduct our experiments on commonlyused portable devices, such as laptops and mobile devices, and in controlled environments.Thus, we cannot guarantee that the results would be the same for different circumstances,such as industrial devices and environments. Lastly, the proposed combinatorial methodinvolves triple combinations. However, higher levels of combinations have not been consid-ered yet. Although this reduces the validity of the experiment, such an extension, pushingthe limits of the scale of the experiment, can be regarded as being beyond the scope of thepaper. However, we believe that our work provides new insights into how to improve thestructure of coding to contribute to green software.

6. Conclusions and Future Remarks

In this study, the impact of code refactoring technique combinations on energy con-sumption has been investigated. The proposed approach has effectively been implementedon 2048 mobile and 2048 desktop application datasets, showing superiority in predictingthe combination of refactoring techniques over previous studies in terms of how the refac-toring techniques should be combined. Moreover, the contribution of the maintainabilitymeasurement values to the energy consumption values of the combinations has also beenlooked into. The proposed method yielded an optimal combination of refactoring tech-niques to keep energy consumption to a minimum. The maintainability index is usefulin choosing combinations of refactoring techniques for the energy consumption of the2048 desktop application. However, this cannot be said for all selected combinations ofthe 2048 mobile application. This is related to the software features of the Java source

Electronics 2022, 11, 442 15 of 17

code used and the interaction of the techniques. For instance, although the Java sourcecode uses loops of specified length and dynamic method invocation as in the C# sourcecode, the overhead of variable declaration resists the energy saved for the 2048 mobileapplication. Therefore, it is necessary to develop complex software metrics including MI toestimate the energy consumption of all combinations. Additionally, the paper provides thefollowing contributions:

1. If the selected refactoring techniques (R1, R2, R3, R4, R5) reduce the energy con-sumption in an application, they will have a positive impact on the three combinedrefactoring techniques (C1, C3, C4).

2. When incompatible refactoring techniques are used together for the source code,energy consumption cannot be reduced as desired.

In future works, we plan to release an upgraded version of the framework for othertypes of programming languages. Moreover, the proposed method will be adapted toproduce a combination of refactoring techniques that do not only consider energy consump-tion but also model the execution time allocated to complete refactoring. Finally, heuristicsand combinatorial methods will be investigated to construct refactoring combinations. Ifhistorical data are recorded, the models forecasting energy consumption help in combiningrefactoring techniques.

Author Contributions: Conceptualization, I.S., M.M.Ö. and T.Y.; methodology, M.M.Ö.; software,I.S.; validation, I.S., M.M.Ö. and T.Y.; formal analysis, I.S.; investigation, I.S.; data curation, T.Y.;writing—original draft preparation, I.S.; writing—review and editing, M.M.Ö. and T.Y.; visualization,I.S.; supervision, M.M.Ö. and T.Y. All authors have read and agreed to the published version of themanuscript.

Funding: This research received no external funding

Data Availability Statement: The data that support the findings of this study are available on requestfrom the corresponding author.

Conflicts of Interest: The authors declare no conflict of interest.

References1. Tolga, A.Ç.; Turgut, Z.K. Sustainable and Renewable Energy Power Plants Evaluation by Fuzzy TODIM Technique. J. Alphanumeric

2018, 6, 49–68.2. Agarwal, S.; Nath, A.; Chowdhury, D. Sustainable approaches and good practices in green software engineering. Int. J. Res. Rev.

Comp. Sci. 2012, 3, 1425.3. Manotas, I.; Bird, C.; Zhang, R.; Shepherd, D.; Jaspan, C.; Sadowski, C.; Pollock, L.; Clause, J. An empirical study of practitioners’

perspectives on green software engineering. In Proceedings of the IEEE/ACM 38th International Conference on SoftwareEngineering (ICSE), Austin, TX, USA, 14–22 May 2016.

4. Barack, O.; Huang, L. Effectiveness of code refactoring techniques for energy consumption in a mobile environment. InProceedings of the International Conference on Software Engineering Research and Practice (SERP), The Steering Committee ofThe World Congress in Computer Science, Computer Engineering and Applied Computing (WorldComp), Las Vegas, USA, 30July-2 August, 2018; pp. 165–171.

5. Anwar, H.; Pfahl, D.; Srirama, S.N. Evaluating the impact of code smell refactoring on the energy consumption of Androidapplications. In Proceedings of the 45th Euromicro Conference on Software Engineering and Advanced Applications (SEAA),Kallithea, Greece, 28–30 August 2019.

6. Park, J.J.; Hong, J.E.; Lee, S.H. Investigation for Software Power Consumption of Code Refactoring. In Proceedings of the TwentySixth International Conference on Software Engineering and Knowledge Engineering (SEKE), Vancouver, Canada, 1–3 July 2014;pp. 717–722.

7. Liu, K.; Pinto, G.; Liu, Y.D.J. Data-oriented characterization of application-level energy optimization. In Proceedings of theInternational Conference on Fundamental Approaches to Software Engineering, London, UK, 11–18 April 2015; pp. 316–331.

8. Sahin, C.; Pollock, L.; Clause, J. How do code refactorings affect energy usage? In Proceedings of the 8th ACM/IEEE InternationalSymposium on Empirical Software Engineering and Measurement, Torino, Italy, 18–19 September 2014; pp. 1–10.

9. Kim, D.; Hong, J.E.; Yoon, I.; Lee, S.H. Code refactoring techniques for reducing energy consumption in embedded computingenvironment. Clust. Comput. 2018, 21, 1079–1095.

10. Taina, J. How green is your software? In Lecture Notes in Business Information Processing; Tyrväinen P., Jansen S., Cusumano M.A.,Eds.; Springer: Berlin/Heidelberg, Germany, 2010; pp. 151–162.

Electronics 2022, 11, 442 16 of 17

11. Naumann, S.; Dick, M.; Kern, E.; Johann, T. The greensoft model: A reference model for green and sustainable software and itsengineering. Sustain. Comput. Inform. Syst. 2011, 1, 294–304.

12. da Silva, W.G.; Brisolara, L.; Corrêa, U.B.; Carro, L. Evaluation of the impact of code refactoring on embedded software efficiency.In Proceedings of the 1st Workshop de Sistemas Embarcados, 2010; pp. 145–150.

13. Gottschalk, M.; Jelschen, J.; Winter, A. Energy-efficient code by refactoring. Softwaretechnik-Trends 2013, 33, 23-24,doi:10.1007/s40568-013-0030-4.

14. Gottschalk, M.; Jelschen, J.; Winter, A. Refactorings for energy-efficiency. In Advances and New Trends in Environmental and EnergyInformatics; Marx Gomez, J., Sonnenschein, M., Vogel, U., Winter, A., Rapp, B., Giesen, N., Eds.; Springer: Cham, Switzerland,2016; pp. 77–96.

15. Morales, R.; Saborido, R.; Khomh, F.; Chicano, F.; Antoniol, G. Earmo: An energy-aware refactoring approach for mobile apps.IEEE Trans. Softw. Eng. 2017, 44, 1176–1206.

16. Sehgal, R.; Mehrotra, D.; Nagpal, R.; Sharma, R.T. Green software: Refactoring approach. J. King Saud Univ.-Comput. Inf. Sci. 2020,in press.

17. Tarwani, S.; Chug, A. Assessment of optimum refactoring sequence to improve the software quality of object-oriented software. J.Inf. Optim. Sci. 2020, 41, 1433–1442.

18. Kaur, S.; Awasthi, L.K.; Sangal, A.L. A review on software refactoring opportunity identification and sequencing in object-orientedsoftware. Recent Adv. Electr. Electron. Eng. 2021, 14, 252–267.

19. Sehgal, R.; Mehrotra, D.; Nagpal, R.; Choudhury, T. Code Smell Refactoring for Energy Optimization of Android Apps. InInnovations in Cyber Physical Systems; Springer: Singapore, 2021; pp. 371–379

20. Coleman, D.; Ash, D.; Lowther, B.; Oman, P. Using metrics to evaluate software system maintainability. J. Comput. 1994, 27, 44–49.21. Connolly Bree, D.; Cinnéide, M.Ó. Inheritance versus Delegation: Which is more energy efficient? In Proceedings of the

IEEE/ACM 42nd International Conference on Software Engineering Workshops, Seoul, Korea, 27 June–19 July 2020; pp. 323–329.22. Agnihotri, M.; Chug, A. A systematic literature survey of software metrics, code smells and refactoring techniques. J. Inf. Process.

Syst. 2020, 16, 915–934.23. Palomba, F.; Di Nucci, D.; Panichella, A.; Zaidman, A.; De Lucia, A. On the impact of code smells on the energy consumption of

mobile applications. Inf. Softw. Technol. 2019, 105, 43–55.24. Counsell, S.; Liu, X.; Swift, S.; Buckley, J.; English, M.; Herold, S.; Eldh, S.; Ermedahl, A. An exploration of the introduce explaining

variable refactoring. In Scientific Workshop Proceedings of the XP2015; ACM: New York, NY, USA 2015; pp. 1–5.25. Fowler, M. Refactoring: Improving the Design of Existing Code; AddisonWesley: Boston, MA, USA, 1999.26. Zotos, K.; Litke, A.; Chatzigeorgiou, A.; Nikolaidis, S.; Stephanides, G. Energy complexity of software in embedded systems.

arXiv 2005, arXiv:nlin/0505007v1.27. Ardito, L.; Coppola, R.; Barbato, L.; Verga, D. A tool-based perspective on software code maintainability metrics: A systematic

literature review. Sci. Prog. 2020, 8, 8840389. http://dx.doi.org/10.1155/2020/8840389.28. Mancebo, J.; García, F.; Calero, C. A process for analysing the energy efficiency of software. Inf. Softe. Technol. 2021, 134, 106560.

https://doi.org/10.1016/j.infsof.2021.106560.29. Pereira, R.; Couto, M.; Ribeiro, F.; Rua, R.; Cunha, J.; Fernandes, J.P.; Saraiva, J. Ranking programming languages by energy

efficiency. Inf. Softw. Technol. 2021, 205, 102609. https://doi.org/10.1016/j.scico.2021.102609.30. Ogala, J.O.; Ojie, D.V. Comparative analysis of c, c++, c# and java programming languages. GSJ 2020, 8, 1899–1913.31. LocMetrics. Available online: https://www.cheonghyun.com/blog/120 (accessed on 10 September 2021).32. Tashtoush, Y.; Al-Maolegi, M.; Arkok, B. The correlation among software complexity metrics with case study. Int. J. Adv. Comput.

Res. 2014, 4, 414–419.33. Kaur, A. Comparative Analysis of Line of Code Metric Tools. Int. J. Sci. Res. Sci. Eng. Technol. 2016, 2, 1285–1288.34. Bhatt, K.; Tarey, V.; Patel, P.; Mits, K.B.; Ujjain, D. Analysis of source lines of code (SLOC) metric. Int. J. Emerg. Technol. Adv. Eng.

2012, 2, 150–154.35. McCabe, T.J. A complexity measure. IEEE Trans. Soft. Eng. 1976, 4, 308–320.36. Shepperd, M. A critique of cyclomatic complexity as a software metric. Softw. Eng. J. 1988, 3, 30–36.37. Joosten, J. The black box testing and loc method approach in testing and streamlining the patient registration program. J. Ris.

Inform. 2021, 3, 137–144.38. Mancebo, J.; Calero, C.; García, F. Does maintainability relate to the energy consumption of software? A case study. Softw. Qual. J.

2021, 29, 101–127.39. Ikerionwu, C. Cyclomatic complexity as a software metric. Int. J. Adv. Acad. Res. 2010, 2, 117–121.40. Najm, N.M.A.M. Measuring Maintainability Index of a Software Depending on Line of Code Only. IOSR J. Comput. Eng. 2014, 16,

64–69.41. JHawk. Available online: http://www.virtualmachinery.com/jhawkprod.htm (accessed on 6 September 2021).42. Intel® Power Gadget. Available online: https://software.intel.com/content/www/us/en/develop/articles/intel-power-gadget.

html (accessed on 2 June 2021).43. Trepn Power Profiler. Available online: https://www.apkmirror.com/apk/qualcomm-innovation-center-inc/trepn-profiler/

(accessed on 12 July 2021).

Electronics 2022, 11, 442 17 of 17

44. Hoque, M.A.; Siekkinen, M.; Khan, K.N.; Xiao, Y.; Tarkoma, S.T. Modeling, profiling, and debugging the energy consumption ofmobile devices. ACM Comput. Surv. (CSUR) 2015, 48, 1–40.

45. Chan-Jong-Chu, K.; Islam, T.; Exposito, M.M.; Sheombar, S.; Valladares, C.; Philippot, O.; Grua, E. M.; Malavolta, I. Investigatingthe correlation between performance scores and energy consumption of mobile web apps. In Proceedings of the Evaluation andAssessment in Software Engineering, Copenhagen, Denmark, 15–17 April 2020, Publisher: Association for Computing Machinery,New York, NY, United States; pp. 190–199.

46. Hindle, A. Green mining: A methodology of relating software change and configuration to power consumption. Empir. Softw.Eng. 2015, 20, 374–409.

47. Aggarwal, K.; Zhang, C.; Campbell, J.C.; Hindle, A.; Stroulia, E. The power of system call traces: predicting the software energyconsumption impact of changes. In Proceedings of 24th Annual International Conference on Computer Science and SoftwareEngineering (CASCON), Markham, Ontario, Canada, 3–5 November 2014; pp. 219–233.

48. Couto, M.; Pereira, R.; Ribeiro, F.; Rua, R.; Saraiva, J. Towards a green ranking for programming languages. In Proceedings of the21st Brazilian Symposium on Programming Languages (SBLP), Fortaleza, CE, Brazil, 21–22 September 2017; ACM, 2017; pp. 1–8.

49. Microsoft Corporation. Available online: https://www.microsoft.com/tr-tr/software-download/windows10 (accessed on 2 July2021).

50. Choudhary, S.R.; Gorla, A.; Orso, A. Automated test input generation for android: Are we there yet? In Proceedings of the 30thIEEE/ACM International Conference on Automated Software Engineering (ASE) , Lincoln, NE, USA, 9–13 November 2015;pp. 429–440.

51. Malavolta, I.; Chinnappan, K.; Jasmontas, L.; Gupta, S.; Soltany, K.A.K. Evaluating the impact of caching on the energyconsumption and performance of progressive web apps. In Proceedings of the IEEE/ACM 7th International Conference onMobile Software Engineering and Systems, Seoul, South Korea, 13–15 July 2020; pp. 109–119.