DEPARTMENT OF COMPUTER SCIENCE
COMP1008 Developing Classes
2006, Graham Roberts
DEPARTMENT OF COMPUTER SCIENCE
Agenda
For the next block of lectures we will be looking at designing and writing an OO program requiring a small number of classes. Along the way we will:
Get an overview of the development process. Learn more about being Object-Oriented. Look at the details of writing classes in Java. Look at more of the Java language. Look at testing.
2006, Graham Roberts
DEPARTMENT OF COMPUTER SCIENCE
Development Activities
Requirements Gathering Requirements Analysis Analysis Design Implementation Testing Delivery, Deployment Maintenance
Requirements List Use Cases
OOA/OOD
OOP
2006, Graham Roberts
DEPARTMENT OF COMPUTER SCIENCE
Process - Organising the Activities
Could work through each activity one after the other?
Wont work!
Need iteration, exploration and experimentation: Analyse a little, Design a little, Code a little, Test a lot Ill be taking a code-centred approach.
In the 2nd & 3rd year Software Engineering courses you will look at process in much greater depth.
2006, Graham Roberts
DEPARTMENT OF COMPUTER SCIENCE
Iterative Programming
Deliver
Requirements
User Needs
Analysis Assess Code Design
Test
5
2006, Graham Roberts
Implement
DEPARTMENT OF COMPUTER SCIENCE
Everything is about design
At different levels of abstraction. Getting all the details correct. Building the correct thing. Confirming it does work. Confirming it does what users actually want/need. Making it work well.
2006, Graham Roberts
DEPARTMENT OF COMPUTER SCIENCE
Good Design/Programming
is hard to do! Trying to predict the future It will work (wont it?) I can program this (cant I?) I dont make mistakes (do I?) I do good quality work (dont I?)
2006, Graham Roberts
DEPARTMENT OF COMPUTER SCIENCE
So,
How do you go about designing and implementing an objectoriented program? How do you know the program code you are writing is: Correct? Good quality? Robust? Reliable? We want to start addressing these issues. You will never stop learning about the answers throughout your professional career. Always expect rapid change.
2006, Graham Roberts
DEPARTMENT OF COMPUTER SCIENCE
Key Issues
Knowing how to test your program. Really knowing how to test your program. Knowing how to design and implement your program. Knowing how to judge the quality of your work (including self assessment). All are hard!
2006, Graham Roberts
DEPARTMENT OF COMPUTER SCIENCE
The Simple Order System
Maintains a list of Customers.
Each Customer has zero or more orders. Each Order consists of one or more LineItems Each LineItem is for a quantity of 1 or more of a specific Product.
Has a simple user interface.
New Customer can be added. New Order can be entered for customer. New Product can be added.
Stores data in files.
2006, Graham Roberts
10
DEPARTMENT OF COMPUTER SCIENCE
Is that all?
Yes, for this iteration.
Get a basic program working, then extend it.
Is this realistic?
To a limited extent, this is an example, focussed on learning Java!
This is a programming course.
For a real program we would do a lot more requirements gathering and data modelling. You will be looking at requirements/analysis modelling and data modelling in a lot more detail in other courses.
But will give an overview here.
2006, Graham Roberts
11
DEPARTMENT OF COMPUTER SCIENCE
Modelling
Construct representations of required behaviour and structure of application. Developed in iterations.
Requirements Use Cases Data modelling/ER diagram
Analysis
Conceptual Model
Design
Code
Detailed Model
2006, Graham Roberts
12
DEPARTMENT OF COMPUTER SCIENCE
Requirements
List, number, organise requirements.
R1: A customer has a first name, family name, postal address, phone number, email address. R2: A product has a code, description and price. ... R10: A new customer can be added by inputting customer details. R11: A new order can be created for a customer (who must already exist). ... R22: A product can be added to an order as a line item. R23: Product quantity can be one or more, combined into the same line item. ...
2006, Graham Roberts
13
DEPARTMENT OF COMPUTER SCIENCE
Use Cases (Stories)
A Use Case describes a task an actor (a user in this example) can perform with the program. Describes what the application should do, not how the code works. Lists steps carried out by actor and responses made by program.
2006, Graham Roberts
14
DEPARTMENT OF COMPUTER SCIENCE
Use Case Example
U1: Add a new customer Actor: User Pre-conditions: main menu displayed Sequence: 1. User selects add customer from menu. 2. Program prompts for user name. 3. User enters name. 4. Program prompts for postal address. ... etc. 10. Program confirms that new customer created. Post-conditions: New customer added. Alternatives: None Errors: 10a: Program reports customer already exists and makes no change.
2006, Graham Roberts
15
DEPARTMENT OF COMPUTER SCIENCE
Analysis
For this example:
Identify key classes and relationships. Following an Object-Oriented approach. Most classes will represent a data item. Construct a Conceptual Model first and then progressively refine. Add methods by identifying how a task is performed by objects.
2006, Graham Roberts
16
DEPARTMENT OF COMPUTER SCIENCE
The Object-Oriented Perspective
Conceptual Diagram, First sketch:
2006, Graham Roberts
17
DEPARTMENT OF COMPUTER SCIENCE
Refinement
Starting to fill in details by working through requirements and use cases. Used an UML modelling tool to create a basic model.
2006, Graham Roberts
18
DEPARTMENT OF COMPUTER SCIENCE
What the tool looks like
2006, Graham Roberts
19
DEPARTMENT OF COMPUTER SCIENCE
Use Cases and Methods
A use case (story) must be implemented via a sequence of method calls between objects of the proposed classes. Consider adding a customer
Input name and details Create customer object Store object somewhere
2006, Graham Roberts
20
DEPARTMENT OF COMPUTER SCIENCE
Fill in details
Input name and details
Need an input method.
Create customer object
What are customer attributes?
Refer back to requirements/use cases: first name, last name, address, phone, email
Store object somewhere
Need a data structure Could use Customer[] or ArrayList<Customer>
Dont know how many customers there will be, so ArrayList is the obvious choice.
2006, Graham Roberts
21
DEPARTMENT OF COMPUTER SCIENCE
Allocate methods
How is behaviour split between methods? Which class does each method belong to? Try: Input method in class SimpleOrderSystem. Store ArrayList<Customer> as instance variable in same class. Constructor for class Customer. What if this is wrong? Backtrack and learn from experience.
2006, Graham Roberts
22
DEPARTMENT OF COMPUTER SCIENCE
Adding an order
Steps
Find customer (can only create order for existing customer) Create Order object
For each item added to an order Select Product (can only order products that exist) Create a LineItem object given product and quantity Add LineItem to Order
Calculate total price and confirm order
LineItem can calculate cost of n items. Order can calculate cost of all LineItems
Add Order to customer
Implies customer has list of orders.
2006, Graham Roberts
23
DEPARTMENT OF COMPUTER SCIENCE
Allocate Methods
Find customer method in class SimpleOrderSystem Input order - sequence of product, amount also method in class SimpleOrderSystem Create LineItem method in class SimpleOrderSystem addItem method needed for class Order Calculate total price Class SimpleOrderSystem seems to be getting quite a Methods in class Order and LineItem few methods. Monitor this for now but may need to Order confirmation take action later. method in class SimpleOrderSystem Add order to customer
2006, Graham Roberts
Can also use ClassResponsibility-Collaboration (CRC) approach - role play method class between objects.
24
DEPARTMENT OF COMPUTER SCIENCE
Wrong Classes?
What if classes and associations dont match with methods?
Missing class Unused class Missing association
Remember an object of one class can only call an object of another class if it has a reference (association) to it.
Modify proposed classes and try again. Iterative process.
2006, Graham Roberts
25
DEPARTMENT OF COMPUTER SCIENCE
Wrong code?
Writing the code validates the design. If the code wont fit together, or is awkward, then iterate and modify design.
Dont be afraid to throw away code.
If its wrong, its wrong.
Dont expect to get design/code right first time (or second time...).
2006, Graham Roberts
26
DEPARTMENT OF COMPUTER SCIENCE
Class Customer (initial version)
public class Customer { private String firstName; private String lastName; ... public Customer(String firstName, String lastName, String address, String phone, String email) { [Link] = firstName; [Link] = lastName; ... } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } ...
2006, Graham Roberts
Omitted other instance variables and methods due to space.
Constructor method. Customer c = new Customer(Arthur, Dent, ...) Constructor method called automatically when object is created. Parameters must be supplied. New object must be initialised using constructor to represent a customer. If constructor omitted, then instance variables initialised by default to null. Object would not be initialised to represent a specific customer.
27
DEPARTMENT OF COMPUTER SCIENCE
Constructor Method Summary
Same name as class name. Cannot return a value, no return type declaration.
Beware public void Customer(...) is a valid instance method but not a constructor.
Is called when an object is created using new.
Parameter list must be provided to match declaration. new returns a reference to the new initialised object.
Cannot be called elsewhere, like an instance method. Is used to properly initialise a new object to its correct state, before the object is used.
2006, Graham Roberts
28
DEPARTMENT OF COMPUTER SCIENCE
No constructor?
If no constructor declared, compiler adds a zero parameter constructor automatically:
public Customer() { } Only want this for very simple classes. Normally you provide a proper constructor.
Instance variables initialised to default values
int, 0 double, 0.0 Any class type (e.g., String), null
2006, Graham Roberts
29
DEPARTMENT OF COMPUTER SCIENCE
Instance Variable Initialisation Idiom
public Customer(String firstName, String lastName, ...) { [Link] = firstName; [Link] = lastName; Instance and parameter variables have same names. Use [Link], to refer to instance variable. Avoids need to invent additional names. But possibly more open to mistakes/confusion.
An idiom is a style or convention a programmer uses when writing code.
2006, Graham Roberts
30
DEPARTMENT OF COMPUTER SCIENCE
class Product
public class Product { private int code; private int price; private String description;
Very straightforward. What if price changes? Will worry about that in a later iteration.
public Product(int code, String description, int price) { [Link] = code; [Link] = price; [Link] = description; } public int getPrice() { return price; } public String getDescription() { return description; } public int getCode() { return code; } }
2006, Graham Roberts
31
DEPARTMENT OF COMPUTER SCIENCE
class LineItem
LineItem has an association with Product. A LineItem has one Product. A Product can be associated with zero or more LineItems. The association is navigable from LineItem to Product. A LineItem knows its Product. A Product is associated with a LineItem but does not know it. LineItem has two attributes, quantity and product. The set of attributes of a class is the combination of those shown inside the icon and the associations. Class LineItem will need two instance variables.
32
2006, Graham Roberts
DEPARTMENT OF COMPUTER SCIENCE
class LineItem (2)
public class LineItem { private int quantity; private Product product; public LineItem(int quantity, Product product) { [Link] = quantity; [Link] = product; } public int getQuantity() { return quantity; } public Product getProduct() { return product; } public int getSubTotal() { return [Link]() * quantity; } }
2006, Graham Roberts
A new LineItem needs a Product and quantity. Hence, constructor has two arguments.
33
DEPARTMENT OF COMPUTER SCIENCE
class LineItem (3)
NOTE
LineItem is given a Product and quantity. It does not create a Product (that happens elsewhere). It does not do any input.
2006, Graham Roberts
34
DEPARTMENT OF COMPUTER SCIENCE
class Order
An Order has one or more LineItems.
Or can an order be empty? Diamond means aggregation association
A LineItem belongs to one Order. Order has two attributes, id and collection of LineItems (via association).
2006, Graham Roberts
35
DEPARTMENT OF COMPUTER SCIENCE
Aggregation and Composition
Both show a one to many relationship between 2 classes. Object of class A holds collection of references to objects of class B.
Aggregation Open diamond Implies A object holds changeable collection of B objects. For our purposes, we are not really interested in the distinction. Can omit diamond entirely.
2006, Graham Roberts
Composition Closed diamond Implies A object owns and controls lifetime of B objects.
36
DEPARTMENT OF COMPUTER SCIENCE
class Order
import [Link]; public class Order { private ArrayList<LineItem> lineItems; public Order() { lineItems = new ArrayList<LineItem>(); } public int getLineItemCount() { return [Link](); } public void add(LineItem item) { [Link](item); } public int getTotal() { int total = 0; for (LineItem item : lineItems) { total += [Link](); } return total; } }
2006, Graham Roberts
37
DEPARTMENT OF COMPUTER SCIENCE
class Order (2)
NOTE (again)
LineItems are added to an Order by passing a reference to an already existing LineItem object. Order does not create LineItems (that happens elsewhere). Order does not do any input.
2006, Graham Roberts
38
DEPARTMENT OF COMPUTER SCIENCE
Back to class Customer
A Customer has a list of Orders. An Order belongs to one Customer. Customer needs an ArrayList<Order> instance variable.
2006, Graham Roberts
39
DEPARTMENT OF COMPUTER SCIENCE
Back to class Customer
Add methods to add an order, get list of orders and get total for all orders (assume this is in the specification).
public void addOrder(Order order) { [Link](order); } public ArrayList<Order> getOrders() { return new ArrayList<Order>(orders); Customer does not } create Orders. Or do any input. public int getTotalForAllOrders() { int total = 0; for (Order order : orders) { total += [Link](); } return total; }
2006, Graham Roberts
40
DEPARTMENT OF COMPUTER SCIENCE
Copying
return new ArrayList<Order>(orders); Remember that return an object really means return a reference to an object. Code the reference is returned to can change the object by calling its methods. The ArrayList is copied but what about the Orders, LineItems and Products? Dont copy - rely on programmer using objects properly? Copy ArrayList only? Copy everything?
2006, Graham Roberts
41
DEPARTMENT OF COMPUTER SCIENCE
class SimpleOrderSystem
Has gained quite a lot of responsibility
Does input/output via terminal Implements high level control
Display menu Manage adding products, orders and customers
Have written a basic working version (see listing). Serves as a framework in which to use classes. BUT
Needs a lot of work before being finished.
2006, Graham Roberts
42
DEPARTMENT OF COMPUTER SCIENCE
public static final
Constant values are declared like this: public static final int ADD_CUSTOMER = 1; static denotes a class variable
belongs to class, one copy shared by all instance objects
final denotes the variable cannot be changed by assignment
it can be directly initialised (as above) or assigned to once if not directly initialised
public denotes that the variable can be accessed from other classes using: SimpleOrderSystem.ADD_CUSTOMER
2006, Graham Roberts
43
DEPARTMENT OF COMPUTER SCIENCE
Using null
private Product getProduct(int code) { for (Product product : products) { if ([Link]() == code) { return product; } } return null; }
Either finds Product object and returns a reference to it, Or, returns null if no Product found with given code. Hence, code calling getProduct (the client code), must check to see if null is returned.
2006, Graham Roberts
44
DEPARTMENT OF COMPUTER SCIENCE
Using null (2)
Product product = getProduct(code); if (product == null) { ... }
null can be compared using == and != If reference == null then no Product object found.
Trying to call method will cause NullPointerException.
If reference != null, Product object found and methods can be called on it. The getProduct method has a contract of use that must be followed.
2006, Graham Roberts
45
DEPARTMENT OF COMPUTER SCIENCE
Exercises 2
Take SimpleOrderSystem code and work with it. Add/modify methods. Find bugs!
Dont assume the code is correct. Read through it and understand how it works.
Use BlueJ.
2006, Graham Roberts
46
DEPARTMENT OF COMPUTER SCIENCE
Compiling the .java files
Each class is stored in a separate .java file. The .java files are located in the working directory. Use javac *.java to compile, or can compile individually.
In fact, the compiler will automatically compile dependent .java files, i.e., if class A uses class B, then compiling [Link] will also compile [Link], if no [Link].
BUT
It would be much better to use BlueJ. Here is a demo...
2006, Graham Roberts
47
DEPARTMENT OF COMPUTER SCIENCE
Summary
Looked at the basic process of designing and writing a small program. Simple classes in Java. Lots of details.
Still many design decisions to be resolved before program is finished.
2006, Graham Roberts
48