0% found this document useful (0 votes)
50 views

Week 9: User-Defined Methods (A Variation From Previous Examples)

The document discusses user-defined methods, program design, and testing methods. It provides examples of defining methods, their parameters and return types. It discusses top-down design with stepwise refinement, including pseudocode examples. It also discusses different types of testing, including black box and white box testing, and provides a simple approach to testing programs by identifying criteria to test inputs, processing, and outputs.

Uploaded by

musa
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
50 views

Week 9: User-Defined Methods (A Variation From Previous Examples)

The document discusses user-defined methods, program design, and testing methods. It provides examples of defining methods, their parameters and return types. It discusses top-down design with stepwise refinement, including pseudocode examples. It also discusses different types of testing, including black box and white box testing, and provides a simple approach to testing programs by identifying criteria to test inputs, processing, and outputs.

Uploaded by

musa
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

CCP3102N

Week 9
User-defined methods (a variation from previous examples)

Let us look at Sum.java (Week 8 Handout) and study how the methods are defined, their
calling point, return type, parameter list etc.

A method groups a number of program statements into a unit and gives it a name. This unit
can then be invoked from other parts of the program.

The most important reason to use methods is as an aid in the conceptual organisation of a
program.

Another reason is to reduce program size. Any sequence of instructions that appears in a
program more than once is a candidate for being made into a method. Methods are used to
define the actions for each class. They are named blocks of code, independent of the rest
of the program, that have a specific purpose. They can be called from elsewhere in the
program.

Program Design

9.1 Program Presentation and Software Design

Over the past few decades, the importance of introducing an industry standard for software
design has been recognised. Much time, effort and money has been lost when somebody
other than the original programmer has had to attempt to re-engineer an existing program
and has found a mass of code with no comments or indentation, little documentation and no
obvious cohesion. With very long programs the task has sometimes been horrendous. Also, it
is not unusual for a team of programmers to work on different aspects of the same system,
making mutual understanding essential. A set of Software Engineering Design principles have
been established to ensure that more than one person can work on the same code with the
minimum of effort.

NB IT IS NO LONGER ACCEPTABLE FOR PROGRAMMERS NOT TO ADOPT GOOD


SOFTWARE ENGINEERING TECHNIQUES.

The design guidelines cover Program Coding and Documentation (including Testing, covered
later in this module).

In writing the program code, they include:-


Cc3102n

INDENTATION - the consistent use of indentation and spacing to make programs


readable and indicate program structure. (NB A 3 space indentation
between each pair of braces is preferred.)

COMMENTS - comments should be used sensibly within a program to improve


understanding and maintenance. This should include a program
name, date and purpose as well as the purpose of each method etc.

UPPER AND LOWER CASE - the consistent use of upper and lower case to improve readability.
(NB Upper Case is used for the first letter of class names and lower
case for the first letter of methods and variable names. InterCapping
naming style - Capital letters are used inside variable names to make
them more readable, e.g. int firstNumber;)

MEANINGFUL IDENTIFIERS – the use of meaningful identifiers for variables, method names
etc., i.e. names that suggest their usage. For example:
String name; // better than String a to store a name;
int age; // better than int y to store an age;

DOCUMENTATION - the use of clear and unambiguous user instructions for the operation
of a program, together with a description of the purpose of the
program and its operation; design documentation; testing details. We
do not cover full documentation in this unit but be aware of its
importance commercially.

9.2 Top Level Design and Stepwise Refinement

From now onwards, you should try to document the design of all your solutions.

The method of design we shall use is called Top Level design with Stepwise Refinement. It is
a pseudo-code approach to problem solving. Pseudocode is a ‘language’ that has been
adopted that enables us to design solutions to problems independently of a programming
language, but enables us to convert the solutions into source code easily. The secret of
finding a solution to a big problem is to break it down into smaller, manageable problems and
to solve these. First, the ‘top level’, we consider a general structure that will answer our
purpose. Then, we expand it, ‘stepwise refinement’, until the problem is solved.

Let’s take Sum1.java, used in an earlier lecture.

Top Level Design for Sum.java


Get two whole numbers from the user
Add them together
Display the answer

2
Cc3102n

This just defines the actions we have to take in simple English. Now, we need to consider
how we will achieve each of them, i.e. add the stepwise refinement.

Top Level Design with Stepwise Refinement


Get two whole numbers from the user
Ask user to enter a whole number
Read it in
Ask user to enter another whole number
Read it in
Add them together
Call method to add the two numbers
Display the answer
Build output String to hold the results
Show the results in a Dialog box

Note the use of indentation showing the design levels. We could expand another level if we
chose to, but, in reality, probably wouldn’t in this case. The greater the expansion, the
closer the pseudocode will resemble source code. The next level would be:

Get two whole numbers from the user


Ask user to enter a whole number
Read it in
Store it as a String
Convert the String to an int
Ask user to enter another whole number
Read it in
Store it as a String
Convert the String to an int
Add them together
Call method to add the two numbers
Return the result
Display the answer
Build output String to hold the results
Show the results in a Dialog box

From here, you should be able to write the source code without any problems. Just work
down the designed solution one line at a time and write the necessary code.

One further advantage can be gained from designing in this way before you start coding and
that is that all the variables you need to use can be identified in advance. Some
programmers add an extra section to the design and identify variables as they go along.
Although not strictly a part of the design, this can be very valuable and save a lot of time. It
also means that you plan the names of your variables and document their use. Below, the
design is repeated, but this time noting the variables that will be needed.

3
Cc3102n

Top Level Design for Sum.java noting variables to be used


Get two whole numbers from the user (String inputString, int number1, int number2)
Add them together (int total)
Display the answer (String output)

This means you know exactly what variables you must declare when you start writing your
source code.

Testing

It is an important software engineering principle and you need to know how to test your
programs.

There are many different methods of testing and many different levels of testing. Basically, a
programmer will do alpha or acceptance testing to check that a program meets the
specification and works correctly. Beta testing is done by typical users who have not been
involved in the development of the program.

We are concerned with alpha testing.

Two main approaches are used, namely black box testing and white box testing.

For black box testing, you look at the specification and develop criteria for testing without
being concerned with the program design. It’s called black box because the code could be
hidden away inside a black box so that you couldn’t see it as you are concerned with testing
that the correct inputs produce the correct results not how the result is produced.

White box testing, so called because it’s the opposite of black box, involves developing test
criteria from the code, e.g. you would test every pathway through a selection statement.
There may be a great many pathways through a program and, except in safety critical
systems, this can be prohibitive because of time and cost.

In reality, a mixture of black box and white box is often used.

Remember, you can only test that within certain constraints a system works correctly,
you cannot guarantee that it will work correctly in every conceivable situation.

A Simple Approach to Testing


It is an important software engineering principle that you test your program and document
the process to aid system maintainability and reengineering.

A simple approach is to identify and number the criteria you will test for.

4
Cc3102n

What should you test for at this stage?


Correct inputs
‘Normal’ data, i.e. something that should be accepted and processed.
‘Abnormal’ data, i.e. a value that should be rejected and error message displayed.
Boundary conditions, i.e. if a number under 100 should be accepted, boundary
conditions would be 99 (should be accepted) and 100 (should be rejected).
Correct processing of data, e.g. any calculations are correctly accomplished.
Loops start and terminate correctly.
Selection structures operate correctly.
All output, including results and error messages are displayed correctly.

Remember, you are testing the inputs, process and outputs.

Sample Exercise:
Write a program, to run as an application, which allows the entry of student marks for a class
and displays summary statistics.

To start, the program should ask the user to enter the total number of students in a class.
This should be no greater than 20. If the user enters 0, the program should terminate. If the
number is less than 0 or greater than 20, an error message should be displayed and the user
should be asked to enter another number. For all other numbers (1 to 20), the user will be
asked to enter a mark out of 100 for each student. For entries less than 0 or greater than
100, an error message should be displayed and repeat entry requested.

After a mark has been entered, a calculation should be done to see what category it falls in
and a count of the total number of each category should be kept. Categories are:

First Class (70 to 100)


Upper Second (60 to 69)
Lower Second (50 to 59)
Third (41 to 49)
Pass (38 to 40)
Fail (0 to 37)

When all of the marks have been entered, an output box should be displayed showing various
statistics, namely:
Number of marks in each category and the percentage that this represents
The average mark (correct to two decimal places)
The highest mark
The lowest mark
Class size

5
Cc3102n

Examples of the input boxes:

Note the student number on the input boxes for marks. These should start at 1 and
increment by 1 until the final entry is made. E.g. for a class size of 5, student numbers would
be 1 to 5.

With entries as follows:


Class size: 16
Marks: 56, 54, 23, 38, 87, 76, 66, 65, 23, 18, 30, 44, 47, 46, 48, 50.

The output box would be:

6
Cc3102n

Note that the percentages have been calculated accurately by ensuring ‘real’ division in the
calculation, but are only displayed as whole numbers. This means that a small degree of
accuracy can be lost in the display with the sum of the individual percentages only totalling
99 instead of 100 because of the rounding. Even though a whole number format for the
display has been used, it is important to calculate the percentage using real division rather
than integer division otherwise incorrect figures will result.

If a number less than 0 or greater than 20 is entered as class size, the following boxes should
appear (one after the other):

If a number less than 0 or greater than 100 is entered as a student mark, the following boxes
should appear:

7
Cc3102n

If 0 (zero) is entered as a class size, the following message should be displayed and then the
program should close down:

Note that only the valid numbers must be included in the calculation. All of the other entries
should result in the appropriate error message being displayed and the user being prompted
to enter another number.

N.B. Your name must appear in the output display box.

Testing
(Based on the above sample exercise example. N.B. This program uses
loops discussed in previous weeks.)

The main criteria:


1) Program accepts correct input for number of students in class:
1.1) accepts numbers 1 to 20 inclusive
1.2) accepts zero
1.3) rejects all other entries, including –1 and 21.
2) Correct error message is displayed for incorrect class size entry and re-entry
requested:
2.1) entries 21 and over
2.2) negative entries
3) Closing message displayed and program is terminated when 0 (zero) is
entered as number of students
4) Program accepts correct input for mark for each student
4.1) input between 0 and 100 inclusive accepted

8
Cc3102n

4.2) negative entry rejected


4.3) numbers of 101 and over rejected
5) Correct error message displayed for incorrect mark entry and re-entry
requested
5.1) negative entries
5.2) 101 and over
6) Calculations are made correctly for
6.1) categories
6.11) number in each category
6.111) first class
6.112) upper second
6.113) lower second
6.114) third
6.115) pass
6.116) fail
6.117) when there is no entry for one or more category
6.118) when there are multiple entries for one or more category
6.119) when incorrect entries have been made at input prompt
6.12) percentage for each category
6.2) highest mark
6.3) lowest mark
6.4) average
6.5) class size
7) Output display is correct
8) Program closes down correctly

Having identified the criteria, you can write a test plan. This is easily presented as a table
(see next page). The reason for the test would not normally be included but it is helpful at
this stage to state it. Also, two extra columns would normally be used, namely, actual result
and date. As we are only dealing with planning, they have been omitted. You are advised to
include these two extra columns when documenting your test results.

The first column, Test No., gives a number to each complete test run, i.e. from running the
program to exiting it. Normally, you would do ‘screen dumps’ (print outs of the screen) to
prove the results, which would be cross referenced to the test using the test number.

Column two shows the criteria numbers taken from the table you have just created. In quite
a small commercial program, these easily run into the hundreds.

Column three shows the data you would input for the test run.

Column four, reason, inserted for clarity only, documents the reason you have selected the
input values. Should you be asked, in an examination for example, to explain why you have
chosen particular values for your tests this is a straightforward method of presenting the
answer.

9
Cc3102n

Column 5, expected result, shows details of what you expect the system to do as a result of
the user action.
Test Table
Test Criteria Data Input Reason Expected Result
No.
1 1.1 16 Normal value for class size Should be accepted and mark for
student number 1 requested.
4.1 56 Normal value for mark Mark accepted & mark for student
54, 23, 38, 87, Normal values to check number 2 requested.
76, 66, 65, 23, that marks for 16 students Marks for 16 students in total
18, 30, 44, 47, are requested and accepted requested and accepted.
46, 48, 50 and values used for
calculations.
6.118, Includes multiple entry for
a category.
6.111, 6.112, Category numbers shown as follows:
6.113, 6.114, First 2
6.115, 6.116 Upper Second 2
Lower Second 3
Third 4
Pass 1
Fail 4
6.12 Percentage calculations Values as follows:
First 12%
Upper Second 12%
Lower Second 19%
Third 25%
Pass 1%
Fail 4%
6.2 Calculation for highest Highest mark 87
mark
6.3 Calculation for lowest Lowest mark 18
mark
6.4 Calculation for average Average 48.19
6.5 Class size Class size 16
7 Output display Output box is displayed with the
above data.
8 Click OK For termination Program closes

NB This is
one test run
from
starting the
program to
program
close
2 1.3, 2.1 21 Boundary incorrect value Error message shown and re-entry
for class size requested.
1.3, 2.2 -1 Negative entry for class Error message shown and re-entry
size requested.
1.1 20 Boundary value for class Accepted and mark requested.
size
4.3, 5.2 101 Boundary incorrect value Error message shown and re-entry

10
Cc3102n

for mark requested.


4.3, 5.2 356 Abnormal value Error message shown and re-entry
requested.
4.2, 5.1 -1 Boundary incorrect value Error message shown and re-entry
requested.
4.2, 5.1, -89 Abnormal value. Incorrect Error message shown and re-entry
6.119 entry at input requested.

4.1, 6.117, 5,5,5,5,5,5,5,5, Multiple normal values for Output box shown with details as
6.118, 7 5,5,5,5,5,5,5,5, mark. Some categories follows:
5,5,5,5 without input. First 0 0
Upper Second 0 0
Lower Second 0 0
Third 0 0
Pass 0 0
Fail 20 100%
Highest mark 5
Lowest mark 5
Average 5
Class size 20
8 OK Program closes
3 1.2, 3 0 Closing value for class Exit message displayed, and when
size OK is clicked, program closes.
A further test run should be included to test ALL normal boundary values for marks, i.e
70 & 100 for first, 60 & 69 for upper second, 50 & 59 for lower second, 41 and 49 for third, 38 and 40 for pass
and 0 and 37 for fail.

Note: You must test for each identified criterion at least once. The first test run will pick
up many of the criteria, further test runs pick up the remaining ones.

Testing Methods
The above table tests the whole program, but it is better to test each method independently
first (called unit testing) and then test the flow of the program as a whole (integration
testing).
Nearly all programs consist of a number of user defined methods. IDE such as BlueJ allows
you to do this by selecting the method from the list displayed when you right-click on the
class in the Design Window. If the method has parameters, BlueJ will ask you to enter values
as arguments, showing you the type for each of them.

Let us consider the addAndDisplay() method from Sum1.java (see Lecture 3). The first stage
is to establish the criteria for testing. As this is a very simple method, the result might be as
follows:

public static void addAndDisplay(int num1, int num2)


Number Criterion
1 Two integers are accepted as arguments
2 They are added together correctly
3 Output box is displayed with “Addition” as title and correct message

Your Test Plan might be:

11
Cc3102n

Test Criteria Data input Reason Expected result


No.
1 1, 4, 15 Normal values Output box
2, displayed with title
3. “Addition” and the
message:
“4 + 15 = 29”
2 1 A, a Abnormal values - Not accepted, error
characters message shown (see
below)
3 1 1.1, 2.345 Abnormal values - Not accepted, error
doubles message shown.

This is the error message that BlueJ


displayed when characters were
entered in place of ints.

N.B. If you had done this in a


program run, you would have got an
exception and your program would
stop operating. Exceptions are not
fully covered within this unit, so it is
important that you test your
methods using the BlueJ Method Call
described in the first paragraph.

As another example, let’s consider your major exercise. Imagine you were required to write
the test plan for the method getNumberOfAdults(), and were given the following table
showing the main criteria:
public static int getNumberOfAdults()
Number Criterion
1 Input Box for number of adults is displayed correctly
2 Only positive numbers or zero are accepted
3 Error message shown and re-entry requested for negative entries

Your Test Plan might be:


Test Criteria Data input Reason Expected result
No.
1 1, 2 4 Normal value Input box displayed
correctly, 4
accepted as number
of adults and
returned by the
method.
2 2 0 Boundary value 0 accepted and

12
Cc3102n

returned.
3 3 -1 Boundary value Error message
shown and re-entry
requested

It is important to start testing your solutions as early as possible. It’s much easier to correct
mistakes in individual methods that have a specific purpose and do not normally have many
lines of code, than it is to test a whole program together. Unit testing allows you to proceed
towards your final solution knowing that the individual elements are working as expected.

This is a simple introduction to a very important software engineering topic. Good testing is a
sign of a good programmer.

EXERCISE – To complete by Week 10:

Choose a problem of your choice and try to complete Top Level Design and Stepwise
Refinement and testing as discussed.

13
Cc3102n

Workshop Exercises:
1. Consider each of the following method calls that might be in the main() method of a
program. In each case write the method header and identify the return type, the
arguments passed to the method and the method parameter list, i.e.

a) { //code in main()
int total = 0, number1 = 4, number2 = 5;
total = add(number1, number2);
//more code
}

Answer:
Method header: int add(int num1, int num2); //you may call num1 and num2
//by different names
The return type is int.
The arguments in main() are number1 and number2.
The method’s parameter list is int num1, int num2.

b) { //code in main()
int number1 = 6, number2 = 7;
add(number1, number2);
//more code
}

c) { //code in main()
int number1 = 6, number2 = 7;
double number3 = 2.5, total = 0.0;
total = add(number1, number2, number3);
//more code
}

d) This example has three method calls but only one method. Identify all three sets of
arguments. There will only be one return type and one parameter list. What value
will total have after the method calls assuming that method adds two integers
together and returns their sum?
{ //code in main()
int number1 = 6, number2 = 7, total = 0;
total = add(number1, number2) + add( 8, 3) – add(number2, 6);
//more code
}

14

You might also like