Upload
others
View
6
Download
0
Embed Size (px)
Citation preview
ii
ABSTRACT
The objective is to develop a prototype of online web application to improve the
quality of the java code using coding conventions. Quality improvement is achieved
through Cyclomatic complexity measures and code coverage. This application permits
the user to upload the java code for code quality improvement. The complexity of the
code is measured on a scale of Cyclomatic complexity range, while the online code
generator improves the code conventions, readability, understandability and
maintainability. Further, automated test cases are generated to improve the efficiency of
the java code by identifying the dead code from the program. The EMMA tool then
shows the efficient code statistics. The EMMA tool is used for measuring and reporting
java code coverage which enables the developers to quickly identify the portions of the
Java code that are not covered by their unit tests. The coverage statistics measure the
quality of the code and shows the improved code report. Hence, the results show that the
improved code is more efficient than the normal code.
iii
TABLE OF CONTENTS
Abstract .............................................................................................................................. ii
Table of Contents ............................................................................................................... iii
List of Figures .................................................................................................................... vi
List of Tables ................................................................................................................... viii
1. Introduction .................................................................................................................1
2. Background…. ............................................................................................................2
2.1 Traditional e-learning……………….................................................................2
2.2 Online compiler application …………………………………………………..3
2.3 Developer Forum ...............................................................................................3
2.4 Challenges ..........................................................................................................4
3. Architecture.................................................................................................................5
3.1 Architecture of web application ….………..…………………………………..6
3.2 Client Design ………………...……………………………………….………6
3.2.1 Cyclomatic complexity ………………………………………….…..…7
3.2.2 Automated test case through Junit Framework ……………………..…9
3.2.3 Improving code coverage through EMMA tool …………………….…11
3.2.4 Online Java code generation and coding conventions ……………..…12
3.3 Admin Design …………………………………………………………..……14
3.4 Data flow ……………………………………………………………………..15
3.5 System context Diagram ………………………………………………..……16
3.6 System Design………………………………………………………………..17
4. Implementation…………………………………………………………………….18
iv
5. Testing, Results and Evaluation………………………………………………………20
5.1 Test case 1 ……………………………………………………..……………20
5.1.1 Normal code ……………………………………………….…………20
5.1.2 Results of the normal code ……………………………………………21
5.1.3 Improved code ………………………………………..………………22
5.1.4 Results of the improved code …………………………………………23
5.2 Test case 2 ………………………………………………..…………………25
5.2.1 Normal code …………………………………………..………………25
5.2.2 Results of the normal code ……………………………………………26
5.2.3 Improved code ……………………………………..…………………28
5.2.4 Results of the improved code …………………………………………29
5.3 Test case 3 ………………………………………………..…………………31
5.3.1 Normal code ……………………………………………………….…31
5.3.2 Results of the normal code ……………………………………………32
5.3.3 Improved code ………………………………………………………..34
5.3.4 Results of the improved code …………………………………………35
5.4 Test case 4 …………………………………………….……………….……37
5.4.1 Normal code …………………………………….……………….……37
5.4.2 Results of the normal code ……………………………………………39
5.4.3 Improved code ……………………………………..…………………42
5.4.4 Results of the improved code …………………………………………44
6. Future work and Conclusion …………………………………………...……………47
6.1 Future Enhancement …………………………………………..………………47
v
6.2 Conclusion ……………………………………………………………….……47
Bibliography …………………………………………………………………………….48
Appendix A. UI screenshots ..............................................................................................50
vi
LIST OF FIGURES
Figure 1. Architecture of a quality centre ...........................................................................6
Figure 2 Nodes and Edges .................................................................................................7
Figure 3 Condition checking ..............................................................................................8
Figure 4 Data flow Diagram ............................................................................................15
Figure 5 System Context Design…………....……………………………...……………16
Figure 6 System Design…………………………….……………………………………17
Figure 7 Junit for test case 1 normal code………….……………………………………21
Figure 8 Coverage for test case 1 normal code …………………………….……………22
Figure 9 Complexity of test case 1 normal code ……………………………..………….22
Figure 10 Junit for test case 1 improved code…………………………………..……….23
Figure 11 Coverage for test case 1 improved code…………………….………………..24
Figure 12 Complexity of test case 1 improved code…………………….………………24
Figure 13 Complexity comparison of normal and improved codes …..…………….…..25
Figure 14 Junit for test case 2 normal code………….………………………….………27
Figure 15 Coverage for test case 2 normal code ………………………….……….……27
Figure 16 Complexity of test case 2 normal code ………………………………………28
Figure 17 Junit for test case 2 improved code…………………………………………..29
Figure 18 Coverage for test case 2 improved code……………………………………..30
Figure 19 Complexity of test case 2 improved code…………………………………….30
Figure 20 Complexity comparison of normal and improved codes ………..…………..31
Figure 21 Junit for test case 3 normal code………….……………………………….…33
Figure 22 Coverage for test case 3 normal code ……………………………………….33
vii
Figure 23 Complexity of test case 3 normal code ………………………………………34
Figure 24 Junit for test case 3 improved code……………………………………….…..35
Figure 25 Coverage for test case 3 improved code………………………………………36
Figure 26 Complexity of test case 3 improved code…………………………….…….…36
Figure 27 Complexity comparison of normal and improved codes …………….…….…37
Figure 28 Junit 1for test case 4 normal code………….…………………………………40
Figure 29 Junit 2for test case 4 normal code……………………………………………41
Figure 30 Coverage for test case 4 normal code ………………………………………..41
Figure 31 Complexity of test case 4 normal code ………………………………………42
Figure 32 Junit 1 for test case 4 improved code……………………………….………..44
Figure 33 Junit 2 for test case 4 normal code………….………………………..………45
Figure 34 Coverage for test case 4 improved code……………………………………..45
Figure 35 Complexity of test case 4 improved code……………………………………46
Figure 36 Complexity comparison of normal and improved codes …………………....46
vii
i
LIST OF TABLES
Table I Cyclomatic complexity table ………………………………………………9
1
1. INTRODUCTION
Various web applications exist for different purposes like e-learning, online shopping, file
sharing application and service providing application like e-blood bank etc. Programming technologies
are improving for efficient development. So, a web application to make the development efficient is
necessary. In software engineering process, code quality is an important aspect taken into consideration
to receive a good feedback from clients. The quality of the software is assessed by a number of
variables that are divided into external and internal quality criteria [1]. The External quality is that a
user experiences when running the software in its operational mode and is critical to the user. The
internal quality refers to the aspects that are code-dependent as well as invisible to the end-user and is
meaningful to the developer. Most of the quality criteria are objective and can be measured
accordingly, whereas some quality criteria are subjective, and are therefore captured with more
arbitrary measurements. Thus, code quality plays an important role in software development. A novice
programmer neither knows how to write a quality code, nor knows about standard format to write the
code [2]. To help the novice programmers and users, a web application is created to receive a normal
code and deliver the improve code. Techniques like Cyclomatic complexity metric and EMMA tool
Code coverage analogy will show the efficiency of the improved code from the normal code sent by the
users.
2
2. BACKGROUND
2.1 Traditional e-learning
Traditional e-learning application focuses on delivering the learning classes for the people and
the organizations over the internet, but most of them do not provide an interactive learning. For
example, user can not only learn the technology but also practice it for proper outcomes. These
applications neither allow the core developers to upgrade their knowledge with interactive quality
measure, nor provide coding conventions to the novice users. Even though it leads to an appraisal of
some widely held ideas regarding the potential for creating modular ‘learning objects’, however, it
lacks many of the quality measures and online compilation ethics which is focused in the proposed
application.
The effectiveness of e-learning depends on establishing two-way communication between the
teachers and the learners, and as well as among learners themselves. However, when e-learning was
first popularized, it was widely promoted as a means of minimizing costs by delivering pre-packaged
content to large population of learners by the means of electronic networks or CD-ROMs. Such an
approach relies on one-way communication from teacher to learner, attenuating the learning experience
[4]. It views learners as atomized individuals and fails to take into account the social context in which
learning occurs.
The proposed web application prototype not only focuses on the two way communication, but
also provides the users with a healthy environment to develop their own code and implement creative
ideas [5]. It also measures the code coverage and improving the code with the help of admin users.
In the existing e-learning sites either user can submit the codes or the developers can measure
the code quality. Whereas the proposed application considers the scenarios of: the user submitting their
query, uploading code and measuring the quality. In addition to these, the application allows the user to
3
generate a code online for classes, packages and interface by selecting the dropdown.
2.2 Online Compiler Application
Online compiler application will provide an executable file on submitting the source file. This
application allows the users to submit source codes developed in different languages like JAVA,
C/C++, FORTRAN, PASCAL and BASIC. On submitting the source code, it will provide the
executable file for the corresponding source code [6]. This application also contains a user interaction
which allows users to submit programming questions and receive answers from the admin or from the
other users of the website. It also contains rating of the user’s questions and source codes as well as
describes library functions of the user-specified built-in-functions in the programming language. For
example, if the user types ‘scanf’ which is a function in c language, the application will display
everything about scanf. Thus, this application helps only to get the compiled code (executable file) of
source code that is submitted and but will not help improve the code.
2.3 Developer Forum
For various programming languages and their applications, developer forums are available to
help the novice programmers and the developers to share their ideas. Different types of programming
languages like java, c/c++, .net and other application oriented languages like JSP, ASP, Java script and
others like android, have their own developer forums to ideas regarding the improvement of these
languages. This developer forum allows the programmers and the learners to share their ideas. Using
developer forum, all the users can submit their queries to get answers from the experts [7]. The queries
posted in the forum can be answered by all the users, which allow the users to interact.
2.4 Challenges:
The primary challenge of online code improvement applications is that, many of the online
4
applications do not understand that 35% of users lack programming experience [8].
Quality and code response lacks in almost all the E-Learning applications
Though some applications provide online video tutorials, they do not allow the user to
simultaneously execute and allow interactive learning.
The existing applications lack in measuring the performance of the code generated by various
developers.
Therefore the proposed application not only focuses on the two way communication but also
allows the users to develop their own code and implement creative ideas by measuring the code
coverage and improving the code.
5
3. Architecture
The purpose of this application is to transform the old java coding ethics into new online code
generation while also measuring the quality based on Cyclomatic complexity and creating automated
Junit test. This application allows the users to submit their java source code online and compile it, as
well as generate the Cyclomatic measure of the code and Junit test cases. In addition, the application
helps the novice users to generate the code online and to keep availing various select and input options
present in the system. Once the user submits the code and checks the complexity, then the submitted
code is improved by the administrator. Administrator checks the functionality and reduces the
complexity by improving its code coverage with the help of EMMA tool. The proposed application
also acts as a learning forum where novice users can submit their queries which are answered on a
timely basis and also can generate code online and compile to check the basic as well as upgraded
coding conventions. The application keeps track of the security authentication of the user submitted
code and provides its accessibility through users account. Once the code is improved, the admin
generates a secret key and sends it to the user via e-mail to achieve security.
6
3.1 Architecture of the web application
Figure1. Architecture of a Quality Centre
The application follows client server architecture model
3.2. Client design:
The following steps are performed on the client side:
1. Cyclomatic Complexity
2. Automated test case through Junit Framework
7
3. Improving code coverage through Emma Tool
4. Online Java Code Generation and Coding Conventions
3.2.1. The Cyclomatic Complexity
This is a software metric which was developed by Thomas J. McCabe in 1976 and it defines the
program inters of a control flow representation. The metric measures the complexity by treating each
independent path of the program i.e. at least one edge which has not been traversed before. It is
calculated with respect to functions, modules, methods or classes in a program.
It represents program as a graph where nodes represent processing tasks and edges represent control
flow between the nodes.
Figure2. Nodes and Edges
Flow Graph representation of a program contains several nodes which are connected through edges.
Below are some of the Flow diagrams for statements like if-else, While, until and normal sequence of
flow.
8
Figure3. Condition checking
Mathematical representation:
Mathematically, it is a set of independent paths connected through the graph diagram. The complexity
of the program can be calculated as:
V(G) = E – N + 2
Where,
E – Number of edges
9
N – Number of Nodes
V (G) = P + 1
When the user submits any java program in the web application after successful compilation, the user
can check code complexity by one click button. Thus the value is mapped in the table below to show
the complexity measure of the submitted code.
Table I. Complexity Table
Complexity Number Meaning
1-10
Structured and well written
code
High Testability
Cost and Effort is less
10-20
Complex Code
Medium Testability
Cost and effort is Medium
20-40
Very complex Code
Low Testability
Cost and Effort are high
>40
Not at all testable
Very high Cost and Effort
Once the Cyclomatic complexity is measured, the user can generate the automated unit test
cases for the submitted code by clicking the Automated Test case button.
3.2.2 Automated test case through Junit Framework
JUnit is a framework that helps in the automation of unit tests for Java classes. It was created by Kent
10
Beck and Erich Gamma. Similar tools for other programming languages are NUnit for the .NET
framework, CppUnit for C++, and PyUnit for Python. The automated test cases of the proposed web
application are built on complete Junit Frame work.
Steps involved in creating unit test cases.
1. Creating Fixture:
Fixture ensures that there is a well known environment in which tests can be run and hence
results are repeatable. For this we have included
Set up () method
Tear down() method
These two are a fixed state of objects used as a baseline for running tests.
2. Creating Test suite:
Test suite is created by giving annotation such as @Test for the methods which are to be tested
in the submitted program. This test suite contains pre initialized fail assert statement as a protocol
which can be updated as per the user’s needs.
Following example depicts how a fail prototype is present in the code:
@Test
public void testPrintMessage() {
System.out.println("Inside testPrintMessage()");
fail(“This just a prototype”);
}
3. Creating the Test Runner:
At the end the test cases are executed through run method. In this way Junit frame work is
implemented and test cases are generated to the user.
11
3.2.3. Improving code coverage through Emma Tool:
Emma is an open source Java code coverage analysis tool that identifies different code paths,
whether they have been executed or not. It generates an HTML report that helps the developers to
identify the code that has been tested. Developers and the users can use the reports to judge the overall
code covered by the tests.
EMMA is a tool for measuring the coverage of the Java code and is essential for detecting dead
code and verifying each part of the application which are exercised by the test suite and interactive use.
EMMA reports rich coverage analyzing the data without introducing the significant overhead during
either build or execution time. At the same time EMMA reports enable fast individual develop-test
cycle, supports quick development and testing of small standalone Java applications, and scales up to
massive enterprise software suites containing thousands of Java classes [5]. EMMA differs from other
coverage tools in its extreme orientation towards fast iterative develop-test style of writing software.
JVM Profiler Interface (JVMPI)-based tools do not require an instrumented source build, but the
runtime overhead of JVMPI is empirically known to be very high and results are exceedingly slow for
test suite runs. For developers using tools based on source code instrumentation, the time required to
conduct a full source code rebuild is not efficient. EMMA's goal is to be unobtrusive and make
frequent daily checks of coverage numbers second nature to every developer, if not a completely
automatic byproduct of every test run.
Until now, the world of Java development had been plagued by an absurd discrepancy: Java
developers had excellent free IDEs, free compilers, and free test frameworks but had to rely on code
coverage tools that charged exorbitant amount and license fee.
EMMA can instrument classes for coverage either offline (before they are loaded) or on the fly (using
an incrementing application class loader). The supported coverage types are class, method, line and
basic block. EMMA can detect when a single source code line is covered partially. Coverage stats are
aggregated at method, class, package, and "all classes" levels. The output report types are plain text,
12
HTML and XML. All the report types support drill-down to a user-controlled detail depth, the HTML
report supports source code linking and the output reports can highlight items with coverage levels
below user-provided thresholds.
EMMA does not require access to the source code and degrades gracefully with decreasing the
amount of debug information available in the input classes [6]. EMMA can instrument individual
.class files or entire .jars (in place, if desired). Efficient coverage subset filtering is possible, too. Make
file and ANT build integration are supported on equal footing. EMMA is quite fast: the runtime
overhead of added instrumentation is small (5-20%) and the byte code instrument of it is very fast
(mostly limited by file I/O speed). Memory overhead is a few hundred bytes per Java class. EMMA is
100% pure Java, has no external library dependencies, and works in any Java 2 JVM (even 1.2.x).
The unreachable code in a program is considered as the dead code. This dead code is
responsible for increasing the complexity of a program. So, the admin removes the dead code identified
by the EMMA. Thus, the quality of the code is improved.
3.2.4. Online Java Code Generation and Coding Conventions
We had implemented the coding ethics and coding conventions where a novice user can select
different options and generate the code online and compile it. The different online programming
constructs available to the user are defined below:
1. Class
2. Interface.
2. Method stub.
3. Setter method.
4. Getter method.
13
Class:
In this sub-module the user can generate properties, methods and the main method of the class.
As soon as the user selects the requirement of generating the code of the class and submits the form via
generate code button, then it redirects to the other page and a code of class is generated automatically.
After generating the code of class the user can compile the code online. The compilation can be done
with the help of a jack tool. During the compilation if the syntax of code of is correct then it displays
“compilation successful” else it displays “compilation unsuccessful” and shows the bug encountered.
Interface:
In this sub-module the user can only generate a code for interface. As soon as the user submits
the form via generate code button, a code for interface is generated automatically.
Method Stub:
In this sub-module the user can only generate a code for method stub. As soon as the user
submits the form via generate code button then a code for Method stub is generated automatically.
Setter Method:
In this sub-module the user can generate properties and setter method for setter method stub.
As soon as the user submits the generate code button then a code of Setter method stub is generated
automatically. When the user select their requirement of generating the code for setter method stub and
submits the form via generate a code button then it redirects to the other page and a code for setter
method is generated automatically. After generating the code of class the user can compile the code.
The compilation can be done with the help of the jack tool. During the compilation if the syntax of
code for setter method is correct then it displays “compilation successful” else it displays “compilation
unsuccessful” and shows the bugs encountered.
Getter method:
In this sub-module the user can generate properties and getter method for getter method stub.
As soon as the user submits the generate code button then a code for Getter method is generated
14
automatically. When the user selects their requirement of generating the code for Getter method Stub
and submits the form via generate code button then it redirects to the other page and a code for Getter
method stub is generated automatically. After generating the code of Getter method stub the user can
compile the code online. The compilation can be done with the help of the jack tool. During the
compilation if the syntax of code for Getter method stub is correct then it displays “compilation
successful” else it displays “compilation unsuccessful” and shows the bugs encountered.
My Account:
As the name suggests it’s an account for the user to see how many files have been uploaded
into the system by the user along with file id. This allows the user to keep track of how many files had
been uploaded in the system and with same file id the user can download the improved code.
3.3. Admin side
On the admin side, code quality will be improved using Cyclomatic complexity, unit testing and
the code coverage statistics. Three techniques are used to improve the code quality, which achieves
readability and understandability of the program code even though read by other developers. This
process enhances the source code appearance. The coding conventions achieve readability by providing
additional information of code usage, providing consistency in development teams making
maintenance easier. Though the coding conventions are applied to improve quality, the code must be
assessed to ensure quality statistics. Unit tests check the correctness of code fragments like methods,
loops and conditional statements. For unit testing Junit is used to improve code quality and also to
detect and reduce the defects in the code. Once improving the code using these two techniques, code
coverage must be determined which can be done using EMMA tool. This will show the coverage
statistics of the improved code. Hence, the improved code achieves the stability and smoothness of the
development cycle as these techniques are applied from the initial level of development. Results will
prove that the improved code is more efficient than the normal code.
15
3.4. Data Flow Diagram:
Figure 4. Data Diagram
16
3.5. System Context Diagram:
Figure 5.System context Diagram
17
3.6 System Design
Figure6: System Design
18
4. IMPLEMENTATION
The application was implemented and tested on NetBeans 7.1 version. Wamp server is used to
host the application, and it accommodates MySql database.
A scope is defined in order to implement the application
1. The uploaded code must be java code
2. Single java file is uploaded at a time
3. Uploaded files must be the default package for all the submitted java files
4. The online code generator compiles the code but does not produce the output
5. The application do not reject the redundant files
6. The mail sent by the admin to the user contains only the secret key, but not the entire improved
java code
Client Side:
The web pages were developed using JSP in Net Beans and the data operations are performed
in MySql. Firstly, the user can post queries without logging into the system. However, to upload the
java code, user must have privileges to access the application or the client must be a registered user.
Further, Cyclomatic complexity value and automated test cases are generated simultaneously. Each
uploaded file has unique field id and all the uploaded files can be viewed in my account page. Finally,
the code generator option provides selective operations to generate a automatic code such as class,
interface, setter method and getter method.
Admin Side:
Apart from basic java script admin has a different login access and a separate table is made up
for admin side details. On successful login admin is able to see the number of queries posted and file
posted. Admin takes the code from the database table and execute again in another IDE where it is
pluginned with Junit and Emma tool. It runs the Junit test cases and finds the complete code coverage
details through EMMA tool. Code coverage statistics data is solely from the EMMA tool which has
19
generated partially and impartially covered paths in the program. Then Admin sends the mail to the
user through smtp protocol of Gmail in the jsp page of sending mail from his mail box to the user with
the status of the uploaded java file. After successful improvisation of code then he will sent a mail to
user with file name and secret code to access the improve file which is maintained on the server in a
separate folder Improve Code with name.
20
5. Testing, Results and Evaluation
4 simulations are run on the test bed and the produced results are compared with the normal code.
5.1. Test case 1:
In this test case, two codes are compared. One is the normal code and the other is the improved
code.
5.1.1 Normal Code:
The following code is to print the status of an individual’s age. The complexity of this code is 10.
package uploadedfiles;
public class Demo2{
public static void main(String args[]){
int age = 29;
if (age < 13)
{
System.out.println("You are a weak child!");
}
else if(age >13 && age <=16)
{
}
else if (age < 19)
{
System.out.println("You are no longer a child, but a teenager.");
}
else
{
if (age < 65)
{
System.out.println("You are an adult!");
}
else
{
System.out.println("You are now a senior, enjoy the good life friends!");
}
System.out.println("Also, since you are over the age of 19, you deserve a drink!");
}
}
public static int calcEquations(int x, int deg) {
return x+deg;
}
}
21
5.1.2 Results of the normal code:
The Junit test case, coverage and complexity measured for the normal code are shown in figures 7, 8
and 9.
Figure 7. Junit for test case 1 normal code
22
Figure 8. Coverage for test case 1 normal code
Figure 9. Complexity of test case 1 normal code
5.1.3 Improved Code:
A ternary operator is replaced in the normal code to improve the quality of the code. The complexity of
the improved code is 2.
package uploadedfiles;
public class ImpDemo2{
public static void main(String args[]){
int age = 29;
System.out.println(age<13?"You are but a wee child!":"You are a sea child");
System.out.println(age<19?"Your are a teen":"You are going uptoa teen");
23
System.out.println(age<50?"Your are growing upto a adult":"You are an old man");
System.out.println("Also, since you are over the age of 19, you deserve a drink!");
}
public static int calcEquations(int x, int deg) {
return x+deg;
}
}
5.1.4 Results of the improved code:
The Junit test case, coverage and complexity measures for the normal code shown in figures 10,11
and 12.
Figure 10. Junit for test case 1 improved code
24
Figure 11. Coverage for test case 1 improved code
Figure 12. Complexity for test case 1 improved
25
The bar graph in the figure 13 shows the reduction of code complexity. The normal code has the
complexity of 10, where as the improved code has the complexity of 2.
Figure 13. Complexity comparison of Normal and Improved codes
5.2.Test 2 .
5.2.1 Normal Code
The following program is to print the ‘head’ or a ‘tail’ when the coin is flipped. The complexity of the
code is 17.
package uploadedfiles;
import java.util.Scanner;
// Asks the user to guess a coin flip
public class CoinFlip {
public static void main(String[] args) {
boolean headsWasSelected = false;
// Prompt user to guess heads or tails
System.out.println("Enter 1 for heads or 2 for tails: ");
Scanner input=new Scanner(System.in);
26
int choice=1;
double randomNumber = Math.random();
switch(choice)
{
case 1:
headsWasSelected = true;
if (headsWasSelected && randomNumber < 0.5)
System.out.println("You win!");
else if (!headsWasSelected && randomNumber >= 0.5)
System.out.println("You win!");
else
System.out.println("Sorry, you lose.");
break;
case 2:
headsWasSelected = false;
if (headsWasSelected && randomNumber < 0.5)
System.out.println("You win!");
else if (!headsWasSelected && randomNumber >= 0.5)
System.out.println("You win!");
else
System.out.println("Sorry, you lose.");
break;
default:
System.out.println("Sorry, you didn't enter heads " +
"or tails; please try again.");
break;
}
// Choose a random number
// Determine whether user guessed correctly
}
}
5.2.2. Results of Normal Code
Figure 14 is a test class for the coin flip program. The values are inputted as per the
user’s choice. By assigning the value as 1, the value is generated as head.
27
Figure 14. Junit test for testcase 2 normal code
Figure 15. Coverage for testcase 2 normal code
28
Figure16. Code complexity of test case 2 normal code
5.2.3. Improved Code
The quality of the code is improved by replacing switch statement with if-else condition. The
complexity of the improved code is 9.
package uploadedfiles;
import java.util.Scanner;
// Asks the user to guess a coin flip
public class CoinFlip2 {
public static void main(String[] args) {
// Prompt user to guess heads or tails
System.out.println("Enter heads or tails: ");
Scanner input=new Scanner(System.in);
String userInput = "heads";
if (!userInput.equalsIgnoreCase("heads") &&
!userInput.equalsIgnoreCase("tails")) {
System.out.println("Sorry, you didn't enter heads " +
"or tails; please try again.");
return;
}
// Choose a random number
double randomNumber = Math.random();
// Determine whether user guessed correctly
if (userInput.equalsIgnoreCase("heads") &&
randomNumber < 0.5)
System.out.println("You win!");
else if (userInput.equalsIgnoreCase("tails") &&
randomNumber >= 0.5)
System.out.println("You win!");
else
29
System.out.println("Sorry, you lose.");
}
}
5.2.4. Results of the improved code
In figure 17, to test the code, the input is head and the program evaluates the results as
expected.
Figure 17. Junit test case for test case 2 improved code
30
Figure 18. Coverage for test case 2 improved code
Figure 19. Complexity for test case 2 Improved code
31
The bar graph in the figure 20 shows the reduction of code complexity. The normal code has the
complexity of 17, where as the improved code has the complexity of 9.
Figure 20. Complexity comparison of Normal and Improved codes
5.3. Test 3
5.3.1 Normal code
The following program is to calculate the average scores. The complexity of this code is 3.
package uploadedfiles;
import java.util.Scanner;
public class AverageScore {
public static void main(String[] args) {
// Prompt user to enter number of scores
System.out.println("Enter number of scores: ");
Scanner input=new Scanner(System.in);
String userInput = "2";
int numberOfScores = Integer.parseInt(userInput);
System.out.println();
// Create array to hold scores
int[] scores = new int[numberOfScores];
32
// Prompt user to enter scores and store them in an array
int i = 0;
while (i < scores.length) {
System.out.println("Enter score #" + (i + 1) + ": ");
userInput = "12";
scores[i] = Integer.parseInt(userInput);
i++;
}
// Compute sum of scores
int sum = 0;
i = 0;
while (i < scores.length) {
sum += scores[i];
i++;
}
// Display average score
System.out.println("\nAverage score: " +
sum / scores.length);
}
}
5.3.2 Results of Test case 3
To test the score we have input the values as 2 and the average of the numbers give the expected result
as actual result. Hence, the test result is 100% passed.
33
Figure 21. Junit test case for test 3 normal code
Figure 22. Coverage for test case 3 normal code
34
Figure 23. Complexity of test case 3 normal code
5.3.3 Improved code
The quality of the code is improved by replacing ‘while’ statement with ‘for’ loop. The complexity of the
improved code is 3.
package uploadedfiles;
import java.util.Scanner;
public class AverageScore2 {
public static void main(String[] args) {
// Prompt user to enter number of scores
System.out.println("Enter number of scores: ");
Scanner input=new Scanner(System.in);
String userInput = input.next().trim();
int numberOfScores = Integer.parseInt(userInput);
System.out.println();
// Create array to hold scores
int[] scores = new int[numberOfScores];
// Prompt user to enter scores and store them in an array
for (int i = 0; i < scores.length; i++) {
System.out.println("Enter score #" + (i + 1) + ": ");
userInput = input.next().trim();
scores[i] = Integer.parseInt(userInput);
}
// Compute sum of scores
int sum = 0;
for (int i = 0; i < scores.length; i++)
sum += scores[i];
// Display average score
System.out.println("\nAverage score: " +
sum / scores.length);
}
}
35
5.3.4. Results of the improved code
This is the test program for the improved code. Here, junit test cases are generated and the code is
tested. Hence, the test result is 100% passed and the program evaluate to expected result.
Figure 24. Junit test case for test 3 improved code
36
Figure 25. Coverage for test case 3 improved code
Figure 26. Complexity for test case 3 improved code
37
The bar graph in the figure 27 shows the code complexity. The normal code has the complexity of 3, as
well as the improved code has the complexity of 3. There exist some scenarios where code complexity
cannot be reduced
Figure 27. Complexity comparison of Normal and Improved codes
5.4. Test 4
5.4.1. Normal Code
The following program is to add and search a contact in the phone directory. The Cyclomatic
complexity of the code is 17.
package uploadedfiles;
import java.util.Scanner;
public class Addressapplication {
public static void main(String[] args) {
PhoneRecord[] records = new PhoneRecord[100];
int numRecords = 0;
// Display list of commands
System.out.println("Phone directory commands:\n" +
" a - Add a new phone number\n" +
38
" f - Find a phone number\n" +
" q - Quit\n");
// Read and execute commands
while (true) {
// Prompt user to enter a command
//Scanner input=new Scanner(System.in);
System.out.println("Enter command (a, f, or q): ");
String command = "a";
// Determine whether command is "a", "f", "q", or
// illegal; execute command if legal.
if (command.equalsIgnoreCase("a")) {
// Command is "a". Prompt user for name and number,
// then create a phone record and store it in the
// database.
if (numRecords < records.length) {
System.out.println("Enter new name: ");
String name = "shravya".trim();
System.out.println("Enter new phone number: ");
String number = "3306317589".trim();
records[numRecords] =
new PhoneRecord(name, number);
numRecords++;
} else
System.out.println("Database is full");
} else if (command.equalsIgnoreCase("f")) {
// Command is "f". Prompt user for search key.
// Search the database for records whose names begin
// with the search key. Print these names and the
// corresponding phone numbers.
System.out.println("Enter name to look up: ");
String key =input.next().trim().toLowerCase();
for (int i = 0; i < numRecords; i++) {
String name = records[i].getName().toLowerCase();
if (name.startsWith(key))
System.out.println(records[i].getName() + " " +
records[i].getNumber());
}
} else if (command.equalsIgnoreCase("q")) {
// Command is "q". Terminate program.
return;
} else {
// Command is illegal. Display error message.
System.out.println("Command was not recognized; " +
"please enter only a, f, or q.");
}
System.out.println();
}
}
}
39
// Represents a record containing a name and a phone number
class PhoneRecord {
private String name;
private String number;
// Constructor
public PhoneRecord(String personName, String phoneNumber) {
name = personName;
number = phoneNumber;
}
// Returns the name stored in the record
public String getName() {
return name;
}
// Returns the phone number stored in the record
public String getNumber() {
return number;
}
}
5.4.2. Results of the normal code
The figure 28 is a test class for the phone address program. In the following program we test
the main method of phone address program of a user. To test we have assigned the values in the
program as name of the user ‘Shravya’ and with respective to the phone number. Hence, the tested code
evaluates the expected result.
40
Figure 28. Junit test case 1 for test case 4 normal code
In the figure 29, junit program is for the second class of improved phone record
program. This is a bean program which is used to set and get the phone numbers and names. To test the
following bean program we have assigned the values in the constructor as ‘aadf’ and
‘2544545’ .Further, these values are matched with expected results giving 100% passed rate.
41
Figure 29. Junit test case 2 for test case 4 normal code
Figure 30. Coverage for test case 4 normal code
42
Figure 31. Complexity of test case 4 normal code
5.4.3 Improved Code
The quality of the code is improved by replacing the infinite looping with switch case condition.
The Cyclomatic complexity of the improved code is 14.
package uploadedfiles;
import java.util.Scanner;
public class ImpAddressapplication {
public static void main(String[] args) {
PhoneRecord1[] records = new PhoneRecord1[100];
int numRecords = 0;
String command = "";
// Display list of commands
System.out.println("Phone directory commands:\n" +
" a - Add a new phone number\n" +
" f - Find a phone number\n" +
" q - Quit\n");
// Read and execute commands
// Prompt user to enter a command
Scanner input=new Scanner(System.in);
System.out.println("Enter command (1 to add, 2 to find, or 3 to exit): ");
int choice=1;
// Determine whether command is "a", "f", "q", or
// illegal; execute command if legal.
switch(choice)
{
case 1:
// Command is "a". Prompt user for name and number,
// then create a phone record and store it in the
// database.
if (numRecords < records.length) {
System.out.println("Enter new name: ");
String name = "shravya".trim();
43
System.out.println("Enter new phone number: ");
String number = "12345".trim();
records[numRecords] =
new PhoneRecord1(name, number);
numRecords++;
} else
System.out.println("Database is full");
Break
case 2:
// Command is "f". Prompt user for search key.
// Search the database for records whose names begin
// with the search key. Print these names and the
// corresponding phone numbers.
System.out.println("Enter name to look up: ");
String key =input.next().trim().toLowerCase();
for (int i = 0; i < numRecords; i++) {
String name = records[i].getName().toLowerCase();
if (name.startsWith(key))
System.out.println(records[i].getName() + " " +
records[i].getNumber());
}
break;
case 3:
System.exit(0);
break;
default:
System.out.println("Command was not recognized; " +
"please enter only a, f, or q.");
} }
// Represents a record containing a name and a phone number
class PhoneRecord1 {
private String name;
private String number;
// Constructor
public PhoneRecord1(String personName, String phoneNumber) {
name = personName;
number = phoneNumber;
}
// Returns the name stored in the record
public String getName() {
return name;
}
// Returns the phone number stored in the record
public String getNumber() {
return number;
}
}
44
5.4.4. Results of the improved code
The figure 31 is a test class for the phone address program. In the following program we test the main
method of phone address program of a user. To test we have assigned the values in the program as
name of the user ‘Shravya’ and with respective to the phone number. Hence, the tested code evaluates
the expected result.
Figure 32. Junit test case 1 for test case 4 improved code
In the figure 33, junit program is for the second class of improved phone record program. This is a bean
program which is used to set and get the phone numbers and names. To test the following bean
program we have assigned the values in the constructor as ‘aadf’ and ‘2544545’ .Further, these values
are matched with expected results giving 100% passed rate.
45
Figure 33. Junit test case 2 for test case 4 improved code
Figure 34. Coverage for test case 4 improve code
46
Figure 35. Complexity of test case 4 improved code
The bar graph in the figure 36 shows the reduction of code complexity. The normal code has the
complexity of 17, where as the improved code has the complexity of 14.
Figure 36. Complexity comparison of normal and improved codes
47
6. FUTUREWORK AND CONCLUSION
6.1 Future Enhancements:
The future work would involve business development applications. In addition, this work
focuses on enhancing the reusable components when user can drag and drop the components such as
packages and interfaces into their application and generate application with time efficiency.
Furthermore, extending this application to a mobile application would make it more accessible.
6.2 Conclusion:
This project presents a complete methodology for e-learning application where the user can
submit the code for improving its quality. It is implemented in the form of a java development forum
where every user can learn the java technology by improving the code and posting the queries. This
project provides java developers to maximize the quality of the code with fewer dead codes. A high
web security is maintained by providing all interactive users by providing secret code.
Proposed web application is implemented over MVC architecture which significantly improves
the performance as well as quality of java code submitted by various types of user under the related test
and compiled environment. It further exhibits significant advantages over existing traditional E-
Learning applications, which lack a dynamic environment where users can not only learn the
programming language but also simultaneously improve the performance. Thus, these existing
applications fail to detect misbehavior and motivate seeds to novice users.
Furthermore, in recent times Programming Assistance Labs (PAL) has gained an important
place in learning programming skills. But, face to face interaction is only the means of guidance in
PAL labs. However, this problem is addressed in this web application by evaluating and guiding the
students online.
48
BIBLIOGRAPHY
[1] Ernst, M. D., Cockrell, J., Griswold, W. G., & Notkin, D. (2001). Dynamically discovering likely
program invariants to support program evolution. Software Engineering, IEEE Transactions on, 27(2),
99-123.
[2] Albrecht, A. J. (1979, October). Measuring application development productivity. In Proceedings of
the Joint SHARE/GUIDE/IBM Application Development Symposium (Vol. 10, pp. 83-92). Monterey,
CA: SHARE Inc. and GUIDE International Corp..
[3] Mccabe, T. (1996). Cyclomatic complexity and the year 2000. Software, IEEE, 13(3), 115-117.
[4] Huang, C. H., & Chen, H. Y. (2005, October). A semi-automatic generator for unit testing code
files based on JUnit. In Systems, Man and Cybernetics, 2005 IEEE International Conference on (Vol.
1, pp. 140-145). IEEE
[5] Ricken, M. G. (2007). A Framework for Testing Concurrent Programs (Doctoral dissertation, Rice
University).
[6] Zhang, L., Marinov, D., Zhang, L., & Khurshid, S. (2011, November). An empirical study of junit
test-suite reduction. In Software Reliability Engineering (ISSRE), 2011 IEEE 22nd International
Symposium on (pp. 170-179). IEEE.
[7] Kong, L., & Yin, Z. (2006, June). The extension of the unit testing tool Junit for special testings. In
Computer and Computational Sciences, 2006. IMSCCS'06. First International Multi-Symposiums on
(Vol. 2, pp. 410-415). IEEE.
[8] Wahid, M., & Almalaise, A. (2011, December). JUnit framework: An interactive approach for basic
unit testing learning in Software Engineering. In Engineering Education (ICEED), 2011 3rd
International Congress on (pp. 159-164). IEEE.
[9] Do, H., Rothermel, G., & Kinneer, A. (2006). Prioritizing JUnit test cases: An empirical assessment
and cost-benefits analysis. Empirical Software Engineering, 11(1), 33-70.
49
[10]Alur, R., Cerný, P., Madhusudan, P., & Nam, W. (2005). Synthesis of interface specifications for
Java classes. ACM SIGPLAN Notices, 40(1), 98-109.
[11]Hovemeyer, D., & Pugh, W. (2004). Finding bugs is easy. ACM Sigplan Notices, 39(12), 92-106.
[12] Kernighan, B. W., & Plauger, P. J. (1978). The elements of programming style. The elements of
programming style, by Kernighan, Brian W.; Plauger, PJ New York: McGraw-Hill, c1978.,
[13] P.Haahr. A Programming Style for Java. http://www.webcom.com/ haahr/, 1998.
[14] http://www.junit.org
[15] http://emma.sourceforge.net/reference/ch02.html
50
APPENDIX
The UI of the application is shown in the following screen shots. The sequence of screen shots shows
the complete functionality of the quality centre web application.
User Manual:
In order to use this application, the user should follow the below steps,
Frigure 1 is the home page of the web application. The user can see the FAQ’s and a login box.
Figure1: Home page
51
In figure 2 the user can post a question and receives the answer in timely basis from the admin.
Figure 2. Secret code via email
52
In figure 3 the user can post the questions related to JAVA
Figure 3. Post a question
Code in Figure 4 shows how the secret code is sent to the user.
Figure 4. Secret code
53
In figure 5, the user log in page has guidelines using which the novice users can develop their code.
User can upload the code here but before uploading the code the user has to include the package
definition with “uploading files “.
Figure 5. Upload the code
54
In the figure 6, the user can compile the code as follows and look for the errors. In this page the total
number of lines in the uploaded code is displayed. Class name and the total number of methods used to
develop a code are generated.
Figure 6. File is uploaded
55
In the figure 7, the Cyclomatic complexity of the code can be viewed in the account. Cyclomatic
complexity measures at different ranges are displayed.
Figure 7. Cyclomatic complexity
56
On hitting the code generator button the user can generate properties, method and main method of the
class. Here the user generated the code for class programming construct. After generating the code the
user can compile the code. If the compilation is successful it displays a message “compilation
successful” else displays “compilation successful” shown in the figure 8.
Figure 8. Option to compile the code
57
All the uploaded files by the user can be checked here in the figure 9.
Figure 9. List of uploaded code
58
In figure 10, the admin page has a login box and admin has to enter his credentials.
Figure 10. Login box for Admin
59
Here the admin has to enter the user information to access the submitted file shown in figure 11.
Figure 11. Accessing the files
60
In the figure 12 the admin has to enter the Qid in order to answer the questions posted by the user.
Figure 12. Answering questions
61
After improving the code the details of the files must be entered and sent to the user via e-mail
generating a secret key shown in figure13.
Figure 13. Send code via mail
62
In the figure 14, the complexity of the code is checked at the admin side.
Figure 14. Improved cyclomatic complexity