Docsity

Java Song Class Development, Study notes of Computer Science

Toggle sidebar
bg1
Chapter 4
Software Development
Warning: This chapter has not been edited yet. It is also incomplete as Rick Considers how
much of the Jukebox should be developed
Chapter Goals
• Find Objects
• Introduce one way to develop software
• Write tests at the same time as writing code
This chapter introduces some techniques that help programmers develop high quality software
that is easy to understand, modify, and maintain. There are many software dev elopment processes
that could be presented here. For example, the traditional “waterfall” approach suggests analysis
and gathering of requirements (figuring out everything the system must do) before all else. Then
the system is designed, which requires a lot of documentation. On l arge projects, analysis and
design can take months (and even years) before a single line of code gets written. Discrete steps
are imposed that require analysis to be complet ed before design, design before coding, and coding
before testing.
This waterfall process also has some severe problems. The development team has to be
almost clairvoyant, with little room for error. Waterfall places the high risk and difficult tasks
toward the end of the project, when it can be too late to debug them.
Craig Larman's book1 provides proof that waterfall has proved to be a terrible way to develop
software. In one study, 87 % of all projects failed. The waterfall process was the "single largest
contributing factor for failure, being cited in 81% of the failed projects as the number one
problem." He quotes a joke about a guy who fell off a cliff:
As he was hurtling down, someone at the top of the cliff yelled to the guy who is falling,
"How are you doing?" The guy replied, "So far, so good!"
1 Agile and Iterative Development: a Manager's Guide, Add ison-Wesley Professional, 2003
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15

Partial preview of the text

Download Java Song Class Development and more Study notes Computer Science in PDF only on Docsity!

Chapter 4

Software Development

Warning: This chapter has not been edited yet. It is also incomplete as Rick Considers how

much of the Jukebox should be developed

Chapter Goals

  • Find Objects
  • Introduce one way to develop software
  • Write tests at the same time as writing code

This chapter introduces some techniques that help programmers develop high quality software

that is easy to understand, modify, and maintain. There are many software development processes

that could be presented here. For example, the traditional “waterfall” approach suggests analysis

and gathering of requirements (figuring out everything the system must do) before all else. Then

the system is designed, which requires a lot of documentation. On large projects, analysis and

design can take months (and even years) before a single line of code gets written. Discrete steps

are imposed that require analysis to be completed before design, design before coding, and coding

before testing.

This waterfall process also has some severe problems. The development team has to be

almost clairvoyant, with little room for error. Waterfall places the high risk and difficult tasks

toward the end of the project, when it can be too late to debug them.

Craig Larman's book^1 provides proof that waterfall has proved to be a terrible way to develop

software. In one study, 87% of all projects failed. The waterfall process was the "single largest

contributing factor for failure, being cited in 81% of the failed projects as the number one

problem." He quotes a joke about a guy who fell off a cliff:

As he was hurtling down, someone at the top of the cliff yelled to the guy who is falling,

"How are you doing?" The guy replied, "So far, so good!"

1 Agile and Iterative Development: a Manager's Guide, Addison-Wesley Professional, 2003

76 Software Development

Recently industry and academia have been adopting an agile approach to software development,

implying less emphasis on documentation. Agile processes still have analysis, design, coding,

testing, and documentation; however these methods emphasize working software as the primary

measure of progress. Software developers work with customers—those wanting the software— in

order to prioritize what is most important Developers code and test to get those features. Design

is employed, but throughout the whole process. Testing is done, but it is done all along.

Some agile practices will now be demonstrated in the context of building a software system.

This narrative describes what the system should be able to do.

The student affairs office has decided to put some newfound activity fee funds toward a

music jukebox in the student center. The jukebox will allow a student to play individual

songs. No money will be required. Instead, a student will swipe a magnetic ID card

through a card reader. Students will each be allowed to play up to 2,000 minutes of

“free” jukebox music in their academic careers at the school. A student may select a

song from the available collection. The user must be able to look up songs by artist and

see how long any song takes to play. No user may play more than two songs on any

given date. No song may be played more than five times on the same date.

One way to begin building this system is to first find the objects. Nouns are potential objects. We

are looking for "things" that may model the desired system. This is not the time to worry about

too many details, or even if you may be right or wrong. A first pass at finding the objects will

represent a list that may end up as part of the system. Others will be eliminated. And still others

may be found later.

A List of Candidate Objects

Jukebox

Student

Song

Card reader

ID card

Collection

Date

While trying to discover useful objects, it helps to eliminate redundant entries. There is no useful

purpose for writing down student more than once, for example. Also, you should include only

those objects that have meaning within the realm of the system. Activity fee funds provide the

money to pay for the Jukebox. However, fees and money need not be developed. We do not need

to build the student center or keep track of the student's academic careers. The seven candidate

objects listed above will do for now.

It is also important to name things as accurately as possible. Although the name Student

appears many times, Student sounds more like an object that might represent the academic career.

JukeboxAccount better represents this new type. SongCollection is more meaningful than

collection. It is also good to recognize those things that are outside of the system that needs to be

developed. The software may play a particular song over the stereo system, but we do not need to

model, nor build, the stereo system—this is outside the system. It also seems like we could use a

way to store all JukeboxAccounts, so it is reasonable to list another candidate object named

JukeboxAccountCollection.

78 Software Development

public class SongTest extends junit.framework.TestCase {

public void testGetters() {

Song song1 = new Song("We Can Work it Out", 135);

Song song2 = new Song("Hard Days Night", 221);

assertEquals("We Can Work it Out", song1.getTitle());

assertEquals(135, song1.getPlaytime());

assertEquals("Hard Days Night", song2.getTitle());

assertEquals(221, song2.getPlaytime());

Once the test exists, write enough code to successfully compile the unit test and the class being

developed, even if the assertions will not pass.

public class Song {

public Song(String songTitle, int playTime) {

public String getTitle() {

return "TBA";

public int getPlaytime() {

return 0;

Run the test with your new code to see the test fail, which is indicated by a red bar^2

2 The screenshots shown here may differ from your environment. These screenshots were captured from

Eclipse 3.1 and the JUnit 3.8.1 testing framework.

Then modify the code to make the tests pass, which will be indicated by a green bar.

public class Song {

// Instance variables to remember data for individual objects

private String title;

private int playTime;

// Construct Song objects so each knows its title and playing time

public Song(String songTitle, int songPlayTimeInSeconds) {

title = songTitle;

playTime = songPlayTimeInSeconds;

// Provide access to the title of this Song

public String getTitle() {

return title;

// Find out how long it will take to play this song

public int getPlaytime() {

return playTime;

The rules of TDD

  • Write the tests first (or later if you can remember, but it’s possible you won't. Try writing

the tests first).

  • Test every method in the class including getters (at least while you are learning).
  • Ensure that all tests run (get the green bar). You may have to change the assertions

because the assertions are wrong—you mistakenly write 237 instead of 236, for example.

assertEquals(27, demoString.length());

If the length of demoString, the actual value is the expected value 27, the assertion is

considered to pass. An assertEquals will fail if the expected value does not equal the expected

value. The first argument is the expected value, and the second argument is the actual value.

The JUnit testing framework version 3.8 has a naming convention to recognize a specific

method as a test (Junit 4 uses the @Test annotation to mark a method as a test). You must declare

a method as public, with a return type of void (which means the method returns nothing). In

Java 3.8, the method name must begin with test (which is case sensitive— Test will not be

recognized) followed by any number of digits (0..9), underscores (_), or other letters ('a'..'z' and

'A'..'Z'). For example, the method name testGetTitle will be recognized as a JUnit test. Here is

one valid test method written as a stub (no code in the body yet):

public void testGetters() {

Next, consider what is needed to construct Song objects. At this point we know the name of the

constructor should be Song(), but we have to decide which (if any) values should be sent to the

constructor as arguments. The test method shows we have decided to have the title as the first

argument and an integer representing the number of seconds of playtime as the second argument.

Remember that we are writing what we need, and we don't care yet if there are compiletime

errors. At this moment there is no Song class or constructor that takes two arguments (a String

and an int). You will see compiletime errors.

public void testGetters() {

// arguments to the constructor: 1) song title 2) playtime in seconds

Song song1 = new Song("We Can Work it Out", (2 * 60) + 15);

Song song2 = new Song("Hard Days Night", 221);

Self-Check

4 - 2 Add the test method above to the unit test SongTest.

The following minimal Song class removes the compiletime errors as long as a newly designed

constructor is included.

public class Song {

public Song(String songTitle, int songPlayTimeInSeconds) {

Self-Check

4 - 3 Create a new class named Song and add the constructor above. Or in Eclipse, select the light

bulbs and have Eclipse write the code for you.

82 Software Development

At this point, assertions can be made in the test method about the desired state of the object

referenced by song1. Someone has to give the method a name, so let's name it getTitle(). We

could change the name if there were a better one (but we won’t at this time). However we do have

to decide if any arguments are required. Deciding the arguments part of the design. Since we are

simply asking the Song objects for the titles, no arguments are required in the getTitle()

method. This test method constructs two objects to show that different objects have their own

state.

import junit.framework.TestCase;

public class SongTest extends TestCase {

public void testGetters() {

Song song1 = new Song("We Can Work it Out", 135);

Song song2 = new Song("Hard Days Night", 221);

assertEquals("We Can Work it Out", song1.getTitle());

assertEquals("Hard Days Night", song2.getTitle());

Self-Check

4 - 4 For the remainder of this chapter add the code presented in boldface, which includes the

two assertions above.

This is what we want, but the getTitle() method does not yet exist. This is a normal part of

TDD. (Actually it is part of all other software development strategies, but perhaps at different

times.) We have now arrived at the time to remove the compiletime errors and proceed; even

knowing the assertions may fail. (Believe it or not, TDD proponents want to see the red bar). The

Song class could now look like this:

public class Song {

public Song(String songTitle, int songPlayTimeInSeconds) {

public String getTitle() {

// Return a bogus value to get the red bar

return "need to store the song title someplace";

Make the assertions fail

Now running the unit test will show that the getTitle() method does not return the correct

value (no surprise). We expected the string value "We Can Work it Out", however the actual

value intentionally returned from the method is this: "need to store the song title

someplace". If you look closely at the results of the test below, you will see there was a test

method that failed: Failures: 1. You will also at the bottom of this screenshot that the expected

84 Software Development

import junit.framework.TestCase;

public class SongTest extends TestCase {

public void testGetTitle() {

Song song1 = new Song("We Can Work it Out", 135);

Song song2 = new Song("Hard Days Night", 221);

assertEquals("We Can Work it Out", song1.getTitle());

assertEquals("Hard Days Night", song2.getTitle());

assertEquals(135, song1.getPlaytime());

assertEquals(221, song2.getPlaytime());

This test method will not compile since getPlayTime() is not yet a method in the Song class.

You might see a compiletime error like this:

The method getPlayTime() is undefined for the type Song

Here are the steps now needed to get the code to compile and make the assertions pass:

1. Add instance variable playTime to Song so all objects remember their own.

2. Initialize this instance variable in the constructor.

3. Make the getPlayTime method return the value of this new instance variable.

public class Song {

// Instance variables

private String title;

// 1. Add an instance variable

private int playTime;

public Song(String songTitle, int songPlayTimeInSeconds) {

title = songTitle;

// 2. Initialize instance variable

playTime = songPlayTimeInSeconds;

public String getTitle() {

return title;

public int getPlaytime() {

// 3. Return the play time for this object

return playTime;

Add More Functionality

One of the requirements for this Jukebox is that no song should be played more than five times on

a given date. One way to manage this is to have each Song correctly respond true or false when

asked if it can be played today. This means we are making the Song responsible for this feature.

The following test method presents one way to do this. Test Driven Development is helping us to

design the class. It specifies two new methods, their names, return types, and arguments.

public void testRecordOnePlayAndCanPlay() { // Times played begins at 0 when constructed Song song1 = new Song("We Can Work it Out", 135); assertTrue(song1.canPlayToday()); song1.recordOnePlay(); song1.recordOnePlay(); song1.recordOnePlay(); song1.recordOnePlay(); assertTrue(song1.canPlayToday()); song1.recordOnePlay(); assertFalse(song1.canPlayToday()); }

Your programming environment should have several errors since two methods, recordOnePlay

and canPlayToday, do not yet exist. Using the same approach as above, we'll add the methods,

instance variables, and algorithms needed to make these assertions pass.

The assertion above suggest what should happen during the messages: canPlayToday

returns true until there have been five recordOnePlay messages. This functionality will be used

by another object to either help play the song or to notify the user that the song has been played

its maximum number of times. We begin with canPlayToday that does not yet increment

songsPlayedToday (so it always returns true):

public class Song {

// Class constant

public static final int MAX_SONGS_PER_DAY = 5;

private int songsPlayedToday;

public Song(String songTitle, int songPlayTimeInSeconds) {

songsPlayedToday = 0;

public boolean canPlayToday() {

return songsPlayedToday < MAX_SONGS_PER_DAY;

if (y1 == y2 && m1 == m2 && d1 == d2)

songsPlayedToday++;

else {

lastPlayDate = currentDate;

songsPlayedToday = 1;

Refactoring

Refactoring refers to making small changes to existing code without changing its meaning. The

intention is to make the code more readable. The current version of recordOnePlay() is

dominated by code that checks to see if the last time this song was played was on the current date.

There is a refactoring named "extract method" that suggests you "Turn the fragment into a

method whose name explains the purpose of the method". A new private helper method is added

that returns true if lastPlayDate is the current date when the message gets sent. This makes

recordOnePlay() easier to read.

public void recordOnePlay() {

if (beenPlayedToday())

songsPlayedToday++;

else {

lastPlayDate = new GregorianCalendar(); // Today

songsPlayedToday = 1;

private boolean beenPlayedToday() {

// Get today's date from the computer's clock

GregorianCalendar currentDate = new GregorianCalendar();

int y1 = currentDate.get(GregorianCalendar.YEAR);

int m1 = currentDate.get(GregorianCalendar.MONTH);

int d1 = currentDate.get(GregorianCalendar.DATE);

int y2 = lastPlayDate.get(GregorianCalendar.YEAR);

int m2 = lastPlayDate.get(GregorianCalendar.MONTH);

int d2 = lastPlayDate.get(GregorianCalendar.DATE);

return (y1 == y2 && m1 == m2 && d1 == d2);

Finishing Song

Imagine that we just reread the spec, or someone just reminded us that we were supposed to be

able to look up songs by artist. It also becomes obvious that we will have to actually play the song

on the computer. It turns out Java can do this given the name of the audio file. Therefore, each

Song object needs to remember the artist and the file name of the audio file.

Song needs two additional instance variables and two methods to get those values. The

constructor needs to be changed to allow the additional data.

Song song1 = new Song("Beatles", "Help", 132, "Help.mid");

88 Software Development

The testGetters method can be increased to include assertions for these two methods (songs

were changed to reflect actual midi files found on the Internet).

public void testGetters() {

Song song1 = new Song("Beatles", "Help", 132, "Help.mid");

Song song2 = new Song("Cheryl Crowe", "Home", 124, "Home.mid");

assertEquals("Help", song1.getTitle());

assertEquals("Home", song2.getTitle());

assertEquals("Beatles", song1.getArtist());

assertEquals("Cheryl Crowe", song2.getArtist());

assertEquals("Help.mid", song1.getAudioFileName());

assertEquals("Home.mid", song2.getAudioFileName());

Self-Check

4 - 5 Replace the testGetters method with the one above.

We'll also add a toString method to return the artist, the title, and the playtime as shown in this

test method:

public void testToString() {

Song song1 = new Song("Beatles", "Help", 132, "Help.mid");

Song song2 = new Song("Cheryl Crowe", "Home", 124, "Home.mid");

assertEquals("Beatles -- 'Help' 2:12", song1.toString());

assertEquals("Cheryl Crowe -- 'Home' 2:04", song2.toString());

The three new methods are shown in this listing of the complete (at least for now) Song class.

  • This class represents one of the Songs that
  • can be played on the cashless Jukebox.
  • @author Rick Mercer / import java.util.GregorianCalendar; public class Song { // A class (only one for all objects) constant (can't be changed) public static final int MAX_SONGS_PER_DAY = 5; // Instance variables private String artist; private String title; private int playTime; private String fileName; private GregorianCalendar lastPlayDate; private int songsPlayedToday; /*
  • Construct a Song object to remember four pieces of
  • information that will be needed by other objects.

90 Software Development

  • Return a textual version of this Song user see at the Jukebox */ @Override public String toString() { // Get the playtime as minutess:seconds with a padded 0 int seconds = getPlaytime(); String mins_secs = seconds / 60 + ":"; if (seconds % 60 < 10) mins_secs += "0"; mins_secs += "" + seconds % 60; return getArtist() + " -- '" + getTitle() + "' " + mins_secs; } // Return true if this song has already been played today private boolean beenPlayedToday() { GregorianCalendar currentDate = new GregorianCalendar(); int y1 = currentDate.get(GregorianCalendar.YEAR); int m1 = currentDate.get(GregorianCalendar.MONTH); int d1 = currentDate.get(GregorianCalendar.DATE); int y2 = lastPlayDate.get(GregorianCalendar.YEAR); int m2 = lastPlayDate.get(GregorianCalendar.MONTH); int d2 = lastPlayDate.get(GregorianCalendar.DATE); return (y1 == y2 && m1 == m2 && d1 == d2); } } Pause: Actually Playing a Song

Without explaining the half dozen new details about playing audio files from a Java application,

here is a class that will play several audio formats (playing mp3 files requires additional

installation). This is followed by a program that will play the song Help by the Beatles assuming

Help.mid is in the correct folder.

import java.applet.Applet; import java.applet.AudioClip; import java.net.MalformedURLException; import java.net.URL; public class SongPlayer { private String baseFolder; private AudioClip audioClip; public SongPlayer(String baseFolder) { this.baseFolder = baseFolder; } public void playSong(Song theSong) { URL url = null; try { url = new URL(baseFolder + theSong.getAudioFileName()); audioClip = Applet.newAudioClip(url); } catch (MalformedURLException e) { System.out.println("bad url " + url); } audioClip.play(); }

// Play one Song stored in this folder's midifiles folder import javax.swing.JOptionPane; public class PlayOneMidiSong { // All songs must be in a folder named midifiles and that // folder must be in the same folder as the Java class files // (or you won't hear the song play) public static final String baseFolder = "file:" + System.getProperty("user.dir") + "/midifiles/"; public static void main(String[] args) { SongPlayer theSongPlayer = new SongPlayer(baseFolder); // Posssible formats: au, wav, aif, mid. // With extra installation, we could play mp3 files! Song theSong = new Song("Beatles", "Help", 132, "Help.mid"); theSongPlayer.playSong(theSong); JOptionPane.showMessageDialog(null, "Stop playing: " + theSong.toString()); // The SongPlayer starts a new thread that will not be shut down // without an explicit call to terminate this program. Without this // static method call, you will have a program running every time // you run this program (songs playing over the others). System.exit(0); } }

Output (in addition to hearing a midi version of 'Help' by the Beatles)

SongCollection

We need to keep track of all songs so they can be shown. A SongCollection type must be able

to do the following:

  • Maintain a collection of all songs that can be played
  • Add a song
  • Remove a song by title

An existing cell remains alive if at time T-1 there were either two or three neighbors.

A cell dies from isolation if at time T-1 there were fewer than two neighbors.

A cell dies from overcrowding if at time T-1 there were more than three neighbors.

A neighborhood consists of the eight elements around any element:

OOO

O O

OOO

The neighborhood can extend to the other side of the society. For example, a location in the first

row has a neighborhood that includes three locations in the last row.

The following patterns would occur when T ranges from 1 to 5, with the initial society shown

at T=1. O represents a live cell; a blank indicates that no cell exists at the particular location in the

society.

T=0 T=1 T=2 T=3 T=

O O O O

OOO O O O O O Society dies off at T=

O O O

Other societies may stabilize like this:

T=0 T=1 T=2 T=3 T=

O O

OOO O OOO O OOO … This pattern repeats …

O O

Implement class GameOfLife along with a unit test. The methods are specified in this

project so you can use the graphical user interface shown at the end of this project. The methods

must exist with the same names, parameters, and return types. For each of the following methods

(except toString), do the following:

  • Add a test method first with calls to non-existent methods
  • Make the test compile (add the method heading and return some bogus return value if

necessary)

  • See the test fail (get the red bar)
  • Write the code necessary to make your tests pass

For example, one simple test method for neighborCount might look like this:

public void testNeighborsWrapping() { GameOfLife society = new GameOfLife(10, 16); society.growCellAt(3, 0); society.growCellAt(3, 15); assertEquals(1, society.neighborCount(3, 15)); assertEquals(1, society.neighborCount(3, 0)); assertEquals(2, society.neighborCount(2, 0)); assertEquals(2, society.neighborCount(4, 0)); assertEquals(2, society.neighborCount(2, 15)); }

94 Software Development

The required methods are provided with the names in boldface. I recommend that you complete

one at a time in the order show.

// Write the constructor so it takes two integer arguments to represent // the number of rows and columns in the game of life. The constructor // creates a society with no cells but space to store rows*cols cells. public GameOfLife (int rows, int cols) // Return the number of usable rows indexed from 0..numberOfRows()- 1 public int numberOfRows () // Return the number of columns indexed from 0..numberOfColumns()- 1 public int numberOfColumns () // Place a new cell in the society. // Precondition: row and col are in range. public void growCellAt (int row, int col) // Return one big string of cells to represent the current state of // the society of cells (see output below where '.' represents an // empty space and 'O' is a live cell. There is no need to // test toString. Simply use it to visually inspect if needed. public String toString ()

Here is one sample output from toString:

GameOfLife society = new GameOfLife(4, 14); society.growCellAt(1, 2); society.growCellAt(2, 2); society.growCellAt(3, 2); System.out.println(society.toString());

Output

..O...........

..O...........

..O...........

// Return true if there is a cell at the given row and column. // Return false if there is none at the specified location. public boolean cellAt (int row, int col) // Count the neighbors around the given location. Use wraparound. // A cell in row 0 has neighbors in the last row if a cell is in the // same column, or the column to the left or right. In this example, // .....O..O // O........ // O.......O // O.......O // ....O.O.. // cell 0,5 has two neighbors in the last row, cell 2,8 has four // neighbors, cell 2,0 has four neighbors, cell 1,0 has three // neighbors. The cell at 4,8 has three neighbors, and the cell // at 3,8 has 3 neighbors. public int neighborCount (int row, int col) // Update the state to represent the next society. public void update ()