Table of Contentsvaklokaal-nlt.nl/wp-content/uploads/2010/10/working_with_eclipse1.pdfInstalling...

27

Transcript of Table of Contentsvaklokaal-nlt.nl/wp-content/uploads/2010/10/working_with_eclipse1.pdfInstalling...

Page 1: Table of Contentsvaklokaal-nlt.nl/wp-content/uploads/2010/10/working_with_eclipse1.pdfInstalling Eclipse The numbers indicating the version of Java are important because you must be
Page 2: Table of Contentsvaklokaal-nlt.nl/wp-content/uploads/2010/10/working_with_eclipse1.pdfInstalling Eclipse The numbers indicating the version of Java are important because you must be

Table of ContentsCHAPTER 1INTRODUCTION ................................................................................... 3CHAPTER 2INSTALLING ECLIPSE.......................................................................... 4

2.1ABOUT JAVA........................................................................................................... 42.2DIFFERENT EDITIONS OF JAVA...................................................................................... 5

CHAPTER 3DOWNLOADING AND INSTALLING JAVA.......................................... 6CHAPTER 4INSTALLING THE ECLIPSE DEVELOPMENT ENVIRONMENT.......... 7

4.1UNIT TESTING.......................................................................................................... 84.2RUNNING THE ECLIPSE ENVIRONMENT............................................................................ 8

CHAPTER 5THE DEVELOPMENT ENVIRONMENT................................................. 95.1GETTING STARTED WITH ECLIPSE ................................................................................ 95.2CREATING A NEW JAVA PROJECT FROM SCRATCH............................................................ 105.3CHOOSING A PERSPECTIVE ...................................................................................... 115.4CREATING A NEW PROJECT FROM EXISTING FILES............................................................ 115.5CREATING A PROGRAM ........................................................................................... 12

5.5.1Creating a new class.................................................................................. 135.6COMPILING AND RUNNING A PROGRAM ....................................................................... 145.7WRITING YOUR FIRST ALGORITHM................................................................................ 155.8DEBUGGING IN ECLIPSE ........................................................................................... 16

5.8.1Setting Breakpoints ................................................................................... 175.8.2Inspecting and changing variables ............................................................ 175.8.3Controlling program execution.................................................................... 18

CHAPTER 6USING JUNIT....................................................................................... 196.1RUNNING A UNIT TEST.............................................................................................. 196.2CREATING TEST CASES........................................................................................... 206.3WRITING THE TEST STATEMENTS................................................................................. 22

6.3.1JUnit Assert statements.............................................................................. 226.4SETTING UP AND TEARING DOWN............................................................................... 23

CHAPTER 7REFACTORING.................................................................................... 247.1WHAT NO RENAME?............................................................................................... 247.2SAMPLE PROGRAM.................................................................................................. 257.3SAMPLE PROGRAM WITH CLASSES............................................................................... 257.4SAMPLE JUNIT TESTCASES....................................................................................... 26

2

Page 3: Table of Contentsvaklokaal-nlt.nl/wp-content/uploads/2010/10/working_with_eclipse1.pdfInstalling Eclipse The numbers indicating the version of Java are important because you must be

Introduct ion

Chapter 1 Introduction

This document is provided to students, following a course in Java development or people interested working with the joBot simulator, which has been developed entirely with Eclipse.

Eclipse is an open source development environment provided by IBM. The simplest way to develop Java programs is of course to use a standard editor and then compile the program using a DOS box to activate the Java compiler using command line statements. This however is cumbersome and error-prone. There are also many very good development tools on the market but in general these are either expensive or their demo versions rather limited.

The Eclipse project, which originated at IBM and is now an open source project, the aim was to develop an open-ended Integrated Development Environment (IDE) that would be able to compete with industry standard products, that would support many different programming languages and that would be free.

Over the past years the facilities of this IDE have reached a status where it has become very popular and has become the tool of choice of many Java developers. Eclipse also allows the development of so-called plugins that you can develop yourself and that allow the IDE to be extended with all sorts of text-editing and graphical tools. A whole range of such tools is currently available among which the most popular are:

• jUnit, an integrated unit testing facility that supports the test-first principle as advocated by the eXtreme Programming community. Eclipse itself was developed using these tools.

• Graphical tools for developing user interfaces. Although only in its first version and still limited, screen painters ease the development of Graphical User Interfaces.

• Tools for the development of UML diagrams. Several of these tools have been developed for the Eclipse IDE and can be found on the Eclipse site.

• Tools for editing, parsing and displaying XML files from a number of suppliers.

The big advantages of the Eclipse IDE is that it is open-source, open-ended allows the editing, compiling, building, debugging and testing of programs in a variety of languages and most importantly, it is for FREE.

3

Page 4: Table of Contentsvaklokaal-nlt.nl/wp-content/uploads/2010/10/working_with_eclipse1.pdfInstalling Eclipse The numbers indicating the version of Java are important because you must be

Instal l ing Ecl ipse

Chapter 2 Installing Eclipse

How you are going to install Eclipse depends somehow on the installation you are using en the environment in which you are installing. Eclipse is not easy to use in a networked environment and therefore in almost all cases we recommend installing the system in the workspace of a local user. This could be your C: or D: drive if it is your own machine, or a network drive like F: or H: on which you need at least 50 Mb of free space. If you are running other programs as well, 100 Mb would be more appropriate.

In some organizations an image of the required Eclipse software and sometimes the joBot and muVium software as well, may be stored on a central server or in an image on the hard disk of your machine. So before you start installing software from a remote site, be sure to check if the required information is already available somewhere in your organization.

Also remember that when you are using the software as part of a group assignment, installing Eclipse in a number of networked machines all at the same time may dramatically increase the download and install time. Under normal circumstances the whole process should take no longer than 15 minutes. However when many people start installing at the same time, using the network drive as a target, installation times may require more than an hour.

Before you can start using Eclipse you will first have to download and install the software, but even before that you have to make sure that you have Java installed on your machine and that the Java Runtime Environment (JRE) can be found by Eclipse.

2.1 About Java

In most cases, Java will already have been installed on your machine. You can check this in a number of ways. The simplest is to check the directory Program Files on you main hard disk for a directory that look like jdk1.4.2_xx or something with jre1.4.2_xx.

One other way is to check the environment variables on your machine and check if the PATH statement contains a reference to a Java directory. This you can do as follows:

Start a DOS box and type in the path statement. You will see something like this. Here you see that a reference has been included to j2sdk1.4.2_xx so this machine contains a version of Java. Although Eclipse should handle the newer 1.5 version of Java, there are some compatibility issues with other parts of the software so for now we recommend not to use Java 1.5 with Eclipse or joBot software.

4

Page 5: Table of Contentsvaklokaal-nlt.nl/wp-content/uploads/2010/10/working_with_eclipse1.pdfInstalling Eclipse The numbers indicating the version of Java are important because you must be

Instal l ing Ecl ipse

The numbers indicating the version of Java are important because you must be using a version that is higher than 1.3. The most recent version of Java is currently 1.5, but lower version will work fine with Eclipse. What version you actually need depends very much on your application and the kind of facilities this needs from the Java environment.

In some cases you may even use a different version of Java to run Eclipse than your application will use that you are developing with Eclipse, but let us not make things more complicated for now.

2.2 Different editions of Java

Apart from the version number of Java, there also are various levels of implementation details. There are a number of editions, called the Standard Edition or the Enterprise Edition. To run Eclipse the Standard Edition is sufficient.

Java editions also come in different levels. The simplest level is the Java Runtime Environment (JRE) that contains everything that you need just to run Java programs. A more extensive (and taking up a whole lot more space) is the Java Development Kit (JDK) that contains many tools to develop software in Java. Since Eclipse however contains most of the tools that you may need, the JRE is sufficient for most cases and certainly for the courses and applications that are using joBot.

5

Page 6: Table of Contentsvaklokaal-nlt.nl/wp-content/uploads/2010/10/working_with_eclipse1.pdfInstalling Eclipse The numbers indicating the version of Java are important because you must be

Downloading and instal l ing Java

Chapter 3 Downloading and installing Java

If your machine does not contain a version of Java, then you need to download and install at least the Java Runtime Environment (JRE).

Fire up your favorite browser and look for the following url: http://java.sun.com

Then download the Java JRE or SDK from and follow the installation instructions.

Make sure your OS has a PATH statement that points to the JDK\bin directory of the installed Java version as you have seen in the DOS box before, or the Eclipse environment will not be able to start.

The Path variable can be found in: My Computer | Properties | Advanced | Environment Variables and then edit the PATH variable in the System Variables.

6

Page 7: Table of Contentsvaklokaal-nlt.nl/wp-content/uploads/2010/10/working_with_eclipse1.pdfInstalling Eclipse The numbers indicating the version of Java are important because you must be

Instal l ing the Ecl ipse Development Environment

Chapter 4 Installing the Eclipse Development Environment

Get the Eclipse IDE and information about it from www.eclipse.org/platformDownload from the download pages two files as specified below.You may have to select a mirror site if the main server is very busy. Once you have located the required download page you will see:

You need to download two zip files from the selected site:

• Download the Eclipse-platform-3.X-win32.zip• Download the Eclipse-JDT-3.X.zip

7

Page 8: Table of Contentsvaklokaal-nlt.nl/wp-content/uploads/2010/10/working_with_eclipse1.pdfInstalling Eclipse The numbers indicating the version of Java are important because you must be

Instal l ing the Ecl ipse Development Environment

The X in the name will actually be the version number which may be 0 or higher.

Installation of Eclipse merely consists of unpacking the files into a working directory. The program is not installed in the usual Windows manner and does not use the registry because Eclipse is a Java program. So if you no longer need it, you may simply delete the Eclipse directory.

4.1 Unit Testing

Unit Testing is a method in which you develop extensive test sets for all important system functions alongside the functionality. In real-time robotic systems this is not always possible but many of the supporting functions can be tested. The JUnit framework allows you to define your tests and have them run automatically while reporting all tests that fail.

Using such a framework makes your code much more reliable and gives you an early warning about things that no longer work as a side-effect of changes intended to repair code elsewhere. In many cases, breaking already working code goes unnoticed and will result in problems some time later than when the changes are made. Such errors are generally hard to find with other methods.

The JUnit facilities are already included in the Eclipse runtime environment.Later in this document a more extensive description of unit testing is included.

4.2 Running the Eclipse environment

Java needs to have been installed before you can run Eclipse. Also the system needs to be able to find the Java runtime environment by including the directory name of the Java runtime in the PATH variable of Windows.

In the installed directory there is a file Eclipse.exe which starts up the Java environment and runs Eclipse. For ease of use place a shortcut to this file on your desktop.The first time you start up, the workbench shows information about the features of Eclipse and some more instructions.

AftA

8

Page 9: Table of Contentsvaklokaal-nlt.nl/wp-content/uploads/2010/10/working_with_eclipse1.pdfInstalling Eclipse The numbers indicating the version of Java are important because you must be

Instal l ing the Ecl ipse Development Environment

After you have explored the new software a bit, click away the tab and you are now ready to start writing your first Java program in the Eclipse environment.

9

Page 10: Table of Contentsvaklokaal-nlt.nl/wp-content/uploads/2010/10/working_with_eclipse1.pdfInstalling Eclipse The numbers indicating the version of Java are important because you must be

The Development Environment

Chapter 5 The Development Environment

5.1 Getting Started with Eclipse

After you have installed Eclipse on your hard disk, for instance on c:\eclipse, you now select the Eclipse icon either from your desktop or from the c:\eclipse directory, which points to eclipse.exe:

The first time you start up Eclipse it will ask you for a workspace. This is a directory that will contain your projects. You can select to use the standard workspace that will be located in the Eclipse directory that you selected, but you may also select a different workspace, which may even contain existing projects.

In most cases selecting the default workspace like c:\eclipse\workspace is the simplest way to get started. Later on we will see how you may enter existing projects into your workspace.

If you are certain that you will want to use this workspace from now on, you may tick the “Use this as the default and do not ask again” box so that Eclipse does not ask for the workspace every time you start up.

After that Eclipse will start and show the main window:

10

Page 11: Table of Contentsvaklokaal-nlt.nl/wp-content/uploads/2010/10/working_with_eclipse1.pdfInstalling Eclipse The numbers indicating the version of Java are important because you must be

The Development Environment

5.2 Creating a new Java project from scratch

Creating a new project without input files is done by selecting File | New.. | Project and you will be asked about the kind of project you want to create:

Here you select a Java Project after which you press the Next button.You are now requested to provide a name for your project.

There are some more options. If you select the “Create separate source and output folders” Eclipse will make sure that your source directory will remain clean from output, which is the preferred situation with our projects.

After that select the “Finish” button and the first time, Eclipse will ask you the following question:

11

Page 12: Table of Contentsvaklokaal-nlt.nl/wp-content/uploads/2010/10/working_with_eclipse1.pdfInstalling Eclipse The numbers indicating the version of Java are important because you must be

The Development Environment

Answer yes and you will see the standard Java perspective.

5.3 Choosing a Perspective

Perspectives are Eclipse’s way of specifying what sub windows will be visible and what the layout is of the main Eclipse window.

A perspective controls what is seen in menus and toolbars. It will contain the editors for source files and a window for properties of these files or of selected objects that are defined in your code, depending on what option you select.

You may easily change perspectives by selecting from the toolbar seen in the upper right corner or by choosing Window, Open Perspective, … from the main menu. For instance, clicking on the double arrow you may select the Java Browsing perspective, which allows you to select portions of an existing project:

12

Page 13: Table of Contentsvaklokaal-nlt.nl/wp-content/uploads/2010/10/working_with_eclipse1.pdfInstalling Eclipse The numbers indicating the version of Java are important because you must be

The Development Environment

5.4 Creating a new project from existing files

During the course or when using the simulator you will often have to load in the code for an existing project. In order to do so, first store the project files in a private directory. Then select File New… | New Project…| Java Project as before and enter a project name.

Now select “Create project at external location” and press the “Browse” button. After that select the directory where the files for your project are located and load them. You will see the directory name appear in the Directory and then press “Finish”. Your project will now appear in the Project Navigator and you may inspect or edit the files that you have loaded into your new project.

13

Page 14: Table of Contentsvaklokaal-nlt.nl/wp-content/uploads/2010/10/working_with_eclipse1.pdfInstalling Eclipse The numbers indicating the version of Java are important because you must be

The Development Environment

To create the XmasTree project, read in the files, listed at the end of the document and run the application from the newly created project. You will get the following output:

5.5 Creating a Program

In the very first lesson we will create a small program to draw a tree on the screen using regular characters. Here are the instructions for a small program that we will be making:

1. Create a new project, called “FirstProject”2. Create a new Class, called “MakeTree”3. Write some code, using a simple iteration function that prints a Christmas tree:

x xxx xxxxx xxxxxxx xxxxxxxxx xxxxxxxxxxxx xx xx

This is your first assignment in which you use a simple loop and the println(“x”); statement to show the output in Eclipse’s console window.

5.5.1 Creating a new class

In order to make the new program, we will need to create a class first.Make sure you create your new project with separated source and object directories, which will be called SRC and BIN by Eclipse by default.

To create a new class, now select File | New | Class

14

Page 15: Table of Contentsvaklokaal-nlt.nl/wp-content/uploads/2010/10/working_with_eclipse1.pdfInstalling Eclipse The numbers indicating the version of Java are important because you must be

The Development Environment

You will get a window in which you fill in the following:

Name it XmasTree or something similar. Please note that class names start with a capital in Java by convention. Make it a public class and select the “Public static void main” box, so the system knows that this class is actually the main class of your new program. You leave the package name blanc and press the “Finish” button.

This is the code that you will see. It is now up to you to create some code in this main function that will print out the tree.

First insert the first statement like this:

System.out.println (“x”);

5.6 Compiling and Running a Program

15

Page 16: Table of Contentsvaklokaal-nlt.nl/wp-content/uploads/2010/10/working_with_eclipse1.pdfInstalling Eclipse The numbers indicating the version of Java are important because you must be

The Development Environment

With your first, very simple program, you now need to compile and than run this program. Compiling is done automatically by Eclipse, every time you save your files. So select File | Save All and this will save your program and compile it at the same time.

To run your program, you must always make sure that the source file, selected in the editor is the file that contains a main method, like is true in our small example.

You then select Run | Run As | Java Application. You may also use the green Run

button in the Toolbar. Select the little arrow on the right side of the green button and select from the pop-up menu the Run As | Java Application.

Eclipse will search for the main method automatically and start the program. You will get an error message when there is no main method or when you have selected the wrong code file. When the program runs, the output will show in the console window at the bottom of the Eclipse Window:

Please note that the row of crosses is now visible in the “Console” window, automatically selected from the “Console” tab.

16

Page 17: Table of Contentsvaklokaal-nlt.nl/wp-content/uploads/2010/10/working_with_eclipse1.pdfInstalling Eclipse The numbers indicating the version of Java are important because you must be

The Development Environment

Remember that Eclipse automatically remembers the most recent program that you ran and stores this under the green “Run” button. So as long as you keep working with the same program, all you now have to do to run a modified version of your

program is to press the button and your program will start.

5.7 Writing your first algorithm

Now that you have seen how to get a program running, write the code to print your first Xmas Tree.

The simplest way of course is to enter a number of print statements, each with the proper number of crosses and spaces in them. Although that is perfectly acceptable, that is not a good way of programming this kind of problem.

When you look at the Xmas Tree you will notice that it starts out with a single cross and then every new line will add two crosses on each side. So to write a loop statement, that iterates a number of times is much simpler and even allows you to draw much bigger trees.

So the first thing you do is to write a statement that initializes the line that you want to print on, like String line = “”;

This variable will contain the line we will want to print. Next we write a loop statement that will first print the initial line and will then after printing, add the crosses to our line.

Something like for(int i=0; i<13; i++) { }

Our print statements will now go inside the brackets.Make sure that you initialize the line with a single x for the first time.After printing, add some crosses to the line this way line = line + “xx”; However, this will misalign the tree, since all crosses will start at the first position. To prevent this, you will have to add a number of spaces to the front of the line, that will get two positions less on every iteration. You can do that exactly the same as with the crosses, by adding a second variable, that will hold the spaces.

Initially this string will have all the required spaces, and on every iteration, you select two spaces less from this string this way:

space = space.substring(1, size);

In size you fill in the decreasing length of the string in space that must be long enough to properly indent each line of your Xmas tree.

At the end of the loop you must now print the trunk of the tree, by two statements that print crosses as the right position and you are done.

What can you now do to make your program behave in such a way that changing a single number, it will print a tree of arbitrary size?

17

Page 18: Table of Contentsvaklokaal-nlt.nl/wp-content/uploads/2010/10/working_with_eclipse1.pdfInstalling Eclipse The numbers indicating the version of Java are important because you must be

The Development Environment

When your program is OK you will see this output:

5.8 Debugging in Eclipse

Often when a program does not work the way you expect, it is useful to be able to use a source-level debugger. Such a debugger lets you look at the sequence in which statements are executed and allows you to inspect the contents of variables and memory locations while the program is executing.

In most cases debugging is done by setting so-called breakpoints that stop the computer program when the breakpoint is reached by the processor.

While operating within the IDE, you can actually see where the program is going, looking at executing step-by-step or running it until a certain point is reached.

In order to debug a program you will have to switch the program to the debugging perspective. We will be debugging a simple version of our XmasTree program.

5.8.1 Setting Breakpoints

In the debug perspective above you see the code area. By double clicking on the print statement inside the for loop, a small circle appears to the left of the code, indicating the position where a breakpoint has been set. We can now start the

18

Page 19: Table of Contentsvaklokaal-nlt.nl/wp-content/uploads/2010/10/working_with_eclipse1.pdfInstalling Eclipse The numbers indicating the version of Java are important because you must be

The Development Environment

program running, but this time we use the Debug As option or the button. We select the Debug As | Java Application option and when the program starts, it will hit the breakpoint and show the line where the breakpoint occurs.

5.8.2 Inspecting and changing variables

By selecting a variable, we may now start looking at the contents of the selected variable. We select line and press the right mouse button. When the pop-up appears we select “inspect” and the variable appears in the “Variables” window at the upper right if the Debug perspective.

The inspector is able to handle simple variables but also entire arrays and objects, so it is easy to follow exactly what is going on in a program. You may actually alter the value of a variable so you may influence the behavior of a running program.

5.8.3 Controlling program execution

When a breakpoint is reached, execution is halted and the statement where the breakpoint was set is highlighted. At the top op the debugging window a number of buttons are visible. These are used to determine what needs to be done next:

These buttons are almost self explanatory. The first set is to continue or stop execution. The buttons with the yellow arrows are used to step into a subroutine or step over a subroutine and allow step-by-step execution this way. Or you may set another breakpoint and continue execution until another breakpoint is hit.

After you are finished debugging you may stop execution with the red button and switch back to the Java perspective.

19

Page 20: Table of Contentsvaklokaal-nlt.nl/wp-content/uploads/2010/10/working_with_eclipse1.pdfInstalling Eclipse The numbers indicating the version of Java are important because you must be

Using JUnit

Chapter 6 Using JUnit

6.1 Running a unit test

In order to run JUnit, you must make sure, you have included the JUnit framework in your project. When you are using the example program this has already been done for you. If not, select the Project Properties and then the “Libraries” tab.

Here you select the “Add External JARs” and browse to the Eclipse\Plugins directory and select the “org.junit_3.8.1”directory and include the junit.jar file in your libraries by selecting it.

Failure to do so, will result in errors in the test module of the XmasTree example.

20

Page 21: Table of Contentsvaklokaal-nlt.nl/wp-content/uploads/2010/10/working_with_eclipse1.pdfInstalling Eclipse The numbers indicating the version of Java are important because you must be

Using JUnit

Now select “Run As … | JUnit Test” and when finished, you select the JUnit window in the explorer bar and will get the following output:

In the Test module you will see a number of Assert statements, that verify the proper operation of the makeLeaf function. If you programmed your function correctly, it will pass the test. If not, you will get a warning.

6.2 Creating Test Cases

When using the Test First approach you will first write a test, run it and see it fail. You the write the accompanying code and will gradually see your code succeed.

But in order to do so, you first need to create the test cases. If you already have some source code that contains the classes you want to test, you may have your test framework code generated for you automatically. Otherwise you first create an empty class for the class under test, or you write a test entirely manually.

First go to the “navigator” and the select File | New | JUnit Test Case. Type in the name of the class you want to test, like “Kerstboom”.

21

Page 22: Table of Contentsvaklokaal-nlt.nl/wp-content/uploads/2010/10/working_with_eclipse1.pdfInstalling Eclipse The numbers indicating the version of Java are important because you must be

Using JUnit

Make sure you include the main, setUp, tearDown and constructor boxes, so Eclipse will generate the proper methods for your test module. From the following window select the methods for which you want the tescases generated. In our case we are mostly interested in the makeLeaf method, so we select it, as well as Kerstboom.

The following code will be generated automatically:

import junit.framework.TestCase;

22

Page 23: Table of Contentsvaklokaal-nlt.nl/wp-content/uploads/2010/10/working_with_eclipse1.pdfInstalling Eclipse The numbers indicating the version of Java are important because you must be

Using JUnit

public class XmasTreeTest extends TestCase {

public static void main(String[] args) {}

protected void setUp() throws Exception {super.setUp();

}

protected void tearDown() throws Exception {super.tearDown();

}

public XmasTreeTest(String arg0) {super(arg0);

}

public void testKerstboom() {}

public void testMakeLeaf() {}

}

In this code framework you may now enter your own test statements under for instance testMakeLeaf.

6.3 Writing the test statements

The tests you write will actually perform a certain function and then verify if the result is as expected. Therefore all tests use an Assert statement, that executes the verification and signals if the result is not as expected.

Because there are many ways in which such a test should be executed, there exists a number of Assert statements, each with its own purpose. We list the most popular here and for more details check the JUnit documentation on www.junit.org.

6.3.1 JUnit Assert statements

For all kinds of compares, different Assert statements do exist like:

Assert.AssertEquals();Assert.AssertTrue();Assert.AssertFalse();Assert.AssertNull();Assert.AssertNotNull();Assert.AssertSame();Assert.AssertNotSame();

In addition you may also catch Exceptions and check if an exception is thrown or not thrown. Sometimes a function should throw an exception and the JUnit framework can catch these and handle them as an assertion.

To test the functioning of the makeLeaf method, we will have to write some code that executes the function and then checks if the output is correct:

23

Page 24: Table of Contentsvaklokaal-nlt.nl/wp-content/uploads/2010/10/working_with_eclipse1.pdfInstalling Eclipse The numbers indicating the version of Java are important because you must be

Using JUnit

public void testMakeLeaf(){

String s="";s = Kerstboom.makeLeaf(0,0);Assert.assertEquals("makeTree(0,0)", "", s);s = Kerstboom.makeLeaf(1,1);Assert.assertEquals("makeTree(1,1)", "*", s);

Here we first allocate a string and call the makeLeaf function with different parameters. The Assert statements verify if the output is as expected. We include such statements for all different configurations that could possibly create a problem.

6.4 Setting Up and tearing Down

Sometimes it may be necessary to prepare your test environment and create a number of objects that your test will act upon.

The setUp and tearDown methods are included for this purpose. Here you may create objects that can be referred to in your tests and when finished with them you may remove them again to prepare the environment for a new test.

You may define as many tests as you like and you may even create entire test suites. For more details check the documentation of JUnit on the site www.junit.org.

24

Page 25: Table of Contentsvaklokaal-nlt.nl/wp-content/uploads/2010/10/working_with_eclipse1.pdfInstalling Eclipse The numbers indicating the version of Java are important because you must be

Refactor ing

Chapter 7 Refactoring

With the practice of eXtreme Programming the development of the simplest version of a program is advocated as a first attempt. While adding more functionality gradually, chances are that sooner or later your program will show a structure clash that needs to be resolved.

There are two ways out of this architectural problem:

• Do proper upfront architectural design an prevent such architectural problems from happening, or

• Accept changes of a structural nature as a fact-of-life and handle it when it occurs.

Both approaches may have their advantages or disadvantages. No amount of upfront design may prevent all such architectural ‘errors’ and therefore there will always be cases where a program needs to be restructured.

The other extreme, when no upfront design is done at all, such changes will occur frequently and may create a lot of unnecessary work. As always the truth will lie somewhere in the middle. Anyway when time comes to restructure your program, Eclipse comes with a number of useful facilities that help you in your restructuring effort. Such restructuring is referred to as “Refactoring”.

When you have created a full set of Test Cases, using JUnit you may actually have a good set of instruments that lets you perform such refactoring work easily, since every change will allow the units test to act as a regression test, that will check, fully automatically if all your code still works as expected after your change. It will pinpoint all cases where your code introduced changes. Without such a full set of regression test, refactoring is not only expensive but rightout dangerous, since you may easily miss these unexpected “side effects”.

7.1 What no Rename?

You will have a hard time, finding the standard “Rename” function that you are used to in other editors. Eclipse however has a “refactor” command that surpasses the rename. It has knowledge about the syntax of Java and when you want to rename a variable, a class or a module, Eclipse knows where it is used and will change all occurrences of the field, using its knowledge about syntax.

With a standard editor, some fields may not be changed at all while some fields that should remain the same do not get changed at all. Eclipse deals with this in a much more elegant way.

25

Page 26: Table of Contentsvaklokaal-nlt.nl/wp-content/uploads/2010/10/working_with_eclipse1.pdfInstalling Eclipse The numbers indicating the version of Java are important because you must be

Refactor ing

7.2 Sample program/** * @author Peter * Simple Version*/public class XmasTree {

public static void main(String[] args) {int size = 8;String line = "x";String space = " ";space = space.substring(1,size+1);String trunk = space.substring(1,size);for (int i = 0; i < size; i++) {

System.out.println(space + line);line = line + "xx";space = space.substring(1, size - i);

}System.out.println(trunk + "xx");System.out.println(trunk + "xx");

}}

7.3 Sample program with classespublic class Kerstboom{

public Kerstboom(){}

private static void makeTree(int size){

String s;for (int i=1; i<15; i=i+2){

s=makeLeaf(i,size);System.out.println(s);

}s=makeLeaf(3,size);System.out.println(s);s=makeLeaf(3,size);System.out.println(s);s=makeLeaf(3,size);System.out.println(s);

}

public static String makeLeaf(int leafSize, int treeSize) { String s=""; int mid = (int) (treeSize-leafSize)/2; for (int i=0; i<mid; i++) { s+=" "; } for (int j=0; j<leafSize; j++) { s+="*"; }

26

Page 27: Table of Contentsvaklokaal-nlt.nl/wp-content/uploads/2010/10/working_with_eclipse1.pdfInstalling Eclipse The numbers indicating the version of Java are important because you must be

Refactor ing

return s; }

public static void main(String[] args){

System.out.println("Kerstboom van Peter");System.out.println();makeTree(15);

}

}

7.4 Sample JUnit testcases

import junit.framework.TestCase;

import junit.framework.*;

public class KerstboomTest extends TestCase{

/** * Constructor for KerstboomTest. * @param arg0 */public KerstboomTest(String arg0){

super(arg0);}

public static void main(String[] args){

junit.awtui.TestRunner.run(KerstboomTest.class);}

public void testMakeLeaf(){

String s="";s = Kerstboom.makeLeaf(0,0);Assert.assertEquals("makeTree(0,0)", "", s);s = Kerstboom.makeLeaf(1,1);Assert.assertEquals("makeTree(1,1)", "*", s);s = Kerstboom.makeLeaf(1,3);Assert.assertEquals("makeTree(1,3)", " *", s);s = Kerstboom.makeLeaf(1,9);Assert.assertEquals("makeTree(1,9)", " *", s);s = Kerstboom.makeLeaf(1,10);Assert.assertEquals("makeTree(1,10)", " *", s);s = Kerstboom.makeLeaf(1,11);Assert.assertEquals("makeTree(1,11)", " *", s);s = Kerstboom.makeLeaf(3,11);Assert.assertEquals("makeTree(3,11)", " ***", s);

}}

27