Comp251 - 01 OL JavaProgrammingBasics

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 36

Comp251 Data Structures & Algorithms

Chapter 1 Java Programming Basics

Java Resources

Java API Specification http://download.oracle.com/javase/6/docs/api/ OReilly ONJava http://www.onjava.com/ Java Tutorial http://download.oracle.com/javase/tutorial/ Java Generics Sun Java Generics Tutorial Angelika Langer Generics FAQs UML Tutorial http://www128.ibm.com/developerworks/rational/library/content/ RationalEdge/sep04/bell/

Ch 01 Objectives

Java Refresher Java Generics Simple Problem Solving Methodology Designing for Larger OO Problems Unified Modeling Language (UML) Static Class Diagrams Design Patterns Readability & Style Testing and Debugging Introduce a Simple Method of Versioning Your Java Code

A Java Refresher

Open

MyMenu.java MyUtil.java

Java Input using Scanner

Review additional methods in the Java API Specification


what each line does, understand the reason behind the choices made in coding it, and the implication of those choices

Be sure that you understand


An Immutable Class
Open XYCoord.java What is an immutable class? When would you use one? What commonly used Java class is also immutable?

Java Generics
A generic type is a type with formal type parameters. A parameterized type is an instantiation of a generic type with actual type arguments.

Generics Examples

A Generic Type
interface Collection<E> { public void add (E x); public Iterator<E> iterator(); }

A Parameterized Type
List<String> list = new LinkedList<String>();

More Than One Type


class Pair<X,Y> private X a; private Y b; {

public Pair(X a, Y b) { this.a = a; this.b = b; } public X getFirst() { return a; } public Y getSecond() { return b; } public void setFirst(X a) { this.a = a; } public void setSecond(Y b) { this.b = b; } }

Practice

Code and test the Pair from the previous slide

5 Step Problem Solving Methodology


1. 2. 3. 4.

5.

State the problem clearly. Describe the input and output. Work it out by hand. Develop an algorithm. Test your solution.

1 Problem Statement
Write a clear and concise statement so as to avoid any misunderstanding EXAMPLE:

Calculate the straight-line distance between two points on a plane

2 Describe the Input and the Output


You need to determine what is needed to produce (calculate) the desired output. Usually its easiest to carefully examine the desired output and think backwards about what you will need to make that happen. Example:

We want to determine the distance between two points on a plane Therefore, we need to know the location of each of those points.

We can use an IO (BlackBox) diagram to visually illustrate this:

3 Hand Example

Now that we have a clear idea of what the input and the output will be we manually calculate the output using the pre-determined input. We may discover that other input is needed an so go back and revise the previous step. The distance between two points is the hypotenuse of a right triangle (see next slide). We can use the Pythagorean theorem to compute the required distance.

distance ( side1 ) 2 ( side2 ) 2 distance (1 6) 2 (3 1) 2 distance 25 4 distance 29 distance 5.39

WARNING: you must NOT proceed to the next step until successful here.

Toggle between this and the next slide

A Plane With Two Points


y

(1, 3)

side1

(6, 1) side2
x

4 Develop an Algorithm
a)

b)

c)

Write out the steps you took in the hand example OPTIONAL: Formalize the steps using pseudocode Translate the pseudocode steps into a programming language.

4a Write out the Steps


1. 2.

3.

4.

Get values for the points Calculate the length of each side of the triangle Calculate the distance between the two points by squaring each side then finding the square root of the square of each side. Print the result (you didnt do this in the hand example but the need to do so is inferred)

4b - Pseudocode
OPTIONAL: not needed unless the programming language has not been determined. Pseudocode is covered in other courses including Comp125

4c Code the Solution


// A program that calculates the distance between two points. // P. Kroeker May 12, 2008
#include <iostream> #include <cmath> using namespace std; int main() { // Declare and initialize variables. double x1(1), y1(3), x2(6), y2(1), side1(0), side2(0), distance(0); // Calculate sides of a right triangle. side1 = x1 x2; side2 = y1 y2; // Calculate the distance distance = sqrt(side1*side1 + side2*side2); // Print out the distance. cout << "The distance between the two points is " << distance << endl; // for cout, endl. // for sqrt()

(coded in C++)

// Exit program (pause so the program output // window doesn't close system("PAUSE"); return EXIT_SUCCESS;
}

5 - Testing

Run the program and the following displays:


The distance between the two points (1,3) and (6,1) is 5.38516.

This is the same as the hand example. If it wasnt, review both hand example and code to determine what went wrong and correct.

Designing for Larger/OO Problems


Simple Problem (previous slides) 1. State the problem clearly. 2. Describe the input and output. 3. Work it out by hand. 4. Develop an algorithm. 5. Test your solution.

More Complex Problem 1. State the problem clearly. 2. Analysis & Design

3. 4.

Describe input, computational needs, output Discover entities, their behaviour & relationships Work it out by hand. Draw UML, write the class specifications

Develop an algorithm. Test your solution.

An OO Analysis/Design Methodology
1. 2. 3. 4. 5. 6. 7. 8. 9.

Write a problem statement AND Restate the problem as a high-level (top-level) algorithm Describe inputs and outputs Identify the objects (look for nouns) Draw the class diagrams Add class associations Refine the (high-level) algorithm; primitive statements become method calls (add to the class diagrams) Add attributes as needed to hold state information Write the Class Specification (s)* NOTE:
All but steps 1&2 are iterative and/or parallel although you may even find that you will edit 1&2 as you complete the others You are NOT writing the code that goes in each method, rather you are clearly understand what each method will do (see class specification notes below) Complete ALL of this BEFORE you begin coding

Class Specification

Purpose statement Invariant statement Attributes Methods (document the task, precondition, modifies, post-condition)
While you are free to use abbreviated documentation for labs you must use the templates on the following slides for formal assignments.

Class Specification
Template for Class Documentation
(Put the following at the beginning of each .java file, remove bracketed text and add your own) /** * AUTHOR: * * CONTACT INFORMATION: * * CREATION DATE: * * VERSION HISTORY: (date and description of each update) * * PROBLEM STATEMENT: (concisely, rephrase the problem) * * PROGRAM DESCRIPTION: (describe your program here referring to * your class diagram as needed) * * CLASS PURPOSE: (a brief desc of the classs purpose) * * CLASS INVARIANT: (what will always be true about this class) */

Class Specification
Template for Method Documentation
(Put the following immediately BEFORE each method, including constructors, remove the bracketed text and add your own) /** * TASK: * * PRECONDITION: * * * MODIFIES: * * * * * POSTCONDITION: * * */

(describe what it does this will help you to complete the next three) (describe what must be true for this method to succeed, includes a description of the formal parameters) (list what will be modified that is external to the method; generally refers to this objects state information but will also include any objects in the formal parameter list that have been modified) (describe what will be true after the method finished, includes a description of the return value)

Design Principles for Classes


Cohesion is a measure of how closely the parts of a component relate to each other Cohesion and Coupling we desire high/strong relationship (internally) are cornerstones of design classes and write methods that do Class design. Review one thing well them for every class and AND everyis a measure of the strength of method you write. Coupling component interconnections we desire low/loose interconnections (externally) make all fields private and consider if methods need to be public

Analysis & Design Tools


Responsibilities entities/actors each having different responsibilities Please make sure that Independence classes & methods youre be comfortable must very independent of others with UML and Class High Cohesion a unit of code (class or method) We will Specification. does just one thing (& does it well) use these extensively. Low Coupling a unit of code (esp a class) is not dependant on other units of code Behaviors each action must be well-understood (again, cohesion) Use UML (Unified Modeling Language) Static Class Diagrams to document

Using UML to Illustrate the Java Generic Sorting Model


interface Comparable +compareTo(in o2 : Object) : int interface Comparator +compare(in o1 : Object, in o2 : Object) : int Collections +sort(in list : List) +sort(in list : List, in comparator : Comparator)

AComparator is an inner class of DataItem interface List DataItem -idNumber : int -description : string AComparator -name : string +DataItem() +compare(in dItem1 : DataItem, in dItem2 : DataItem) : int +getID() : int 0..* +getName() : string +getDescription() : string +compareTo(in dataItem2 : DataItem) : int +other methods . . .() 1 DataController -inventory : List 1 ArrayList 1

UML Tool

Get hooked up with MSDN and get MS VISIO. Here is an Open Source UML modeling tool thats somewhat easier to get going on than VISIO.

Warning it has some limitations (I cant recall what)

Code Design

Class-Responsibility-Collaborator (CRC) cards (index cards)


Name of component at top Responsibilities at left Collaborators at right We cycle through action/actor until all actions have actors

Design Patterns well know ways of coding things

Design Pattern Categories


Fundamental high level patterns. Functional Pattern Cohesion/Coupling Creational object creation Singleton Factory Method Structural ease design by identifying a simple way to realize relationships between entities. Adaptor Decorator Behavioural identify common communication patterns between objects. Iterator Observer Concurrency multithreading patterns read more here

Pseudo-Code

Pseudo-code can be used to describe what methods do once they are generically understood

Writing out (part of the class spec)


Task Precondition Modifies Post condition

Coding

Now we can start writing the code BUT REMEMBER, NOT until all the thought and documentation that goes into designing the solution is complete Why?

Readability & Style

Review
Comp251_Commenting.docx (same as slide 23 and 24) Text: end of section 1.9.3 (pg 52 53)

Remember that the standards set out in the above file are mandatory for assignment submissions.

Testing & Debugging

Testing
If possible each statement should be tested. Is this always practical? Special cases of input

Text: section 1.9.4 (pg 53)


Boundary testing

Debugging
Print statements Debugger

Organizing and Versioning Code


Always save a progressing set of running versions of your code as you work on a problem The easiest way is to create a set of folders (next slide) Why would you do this?

Organizing and Versioning Code


The location where you will keep your code The name of the project, lab, etc The very first attempt Refining attempts, until The first functional version (may be a delivery version) Refining versions

A Major revision
Followed by further refining and further major revisions. (Not Shown)

You might also like