Traditional (non-object-oriented) Programming based on an algorithmic approach with programs...
-
date post
21-Dec-2015 -
Category
Documents
-
view
216 -
download
0
Transcript of Traditional (non-object-oriented) Programming based on an algorithmic approach with programs...
Traditional (non-object-oriented) Programming
• based on an algorithmic approach with programs consisting of lines of code organized around various programming structures such as loops/if..then..else/goto
• Lots of code
• Flow charts as design tool, spaghetti code
Structured programming
• Code using well defined program structures to avoid spaghetti code
• Structures: single entry, single exit, no goto • Top-down programming using functions and
procedures. • Code would be organized into modules or
groupings of functions, with a typical large program having many modules (each with a .h file) and carefully specified rules for using the functions.
Data Structures
• Typical program would define data structures (variables, arrays, structs ) to model the situation.
• Usually these would be in some global context. Although frequently defined in code modules, would in fact be one global context.
• Some data structures might have special functions to handle them, like adding to a list, but often these would be specific to the particular kind of structure in the program.
• Code, in general, would act on the data structures to produce the application.
• Data Structures would be very application specific, as a rule.
Pig GameGame of Pig
2 players, one pair of dice
Object: Be the first player to accumulate a total of 100 points by rolling the dice.
The play:
A. Players alternate turns attempting to accumulate points.B. A turn consists of 1 or more rolls of the dice and the points are accumulated.C. When a turn ends, accumulated points are added to the game total for that player. D. If on any roll of a turn, one of the dice is a 1, then all points accumulated on that turn are forfeit, and the turn ends.E. If the player rolls snake-eyes (two 1's) then the player loses all points for the round and all points accumulated in the game, and the turn ends.F. The player may choose to end a turn and pass the dice at any point after the first roll or may be a Pig and roll again.
Variation for computer play: F1: the computer must pass the dice if it accumulates 20 points or more on a turn, but it must otherwise roll the dice if possible (subject to rules D and E)
Data Structures
Begin by defining data structures (variables). int humanscore=0; int humanroundtotal;
//other vars to describe humanint computerscore=0
//other vars for computerint computerroundtotal;
//Dice variables.int die1, die2;int rollTotal;
Code manipulates the datawhile(humanscore < 100 && computerscore < 100){ //human turn while (turnNotOver) { //roll dice (die1=RollDie(); die2=RollDie()l;
//process roll (update variables like humanroundtotal) //display result //if allowed by rules to continue then ask //if not continuing then update score // turnNotOver=false; } //if human hasn't won then computer turn //similar code but instead of asking we just check the round total }
Each pseudo-code line might be a function (method).
Some difficulties
• Namespaces …. Hard to guarantee unique variable names especially with multiple programmers contributing
• Reusability …. Hard to reuse code since everything became tended to be special purpose. Reuse ideas…’borrow’ code and make changes for your app
• Maintainability .. Logical relationships often difficult to piece together. Code can be hard to understand and modify.
Coding Standards
• Depended a lot on coding standards within an organization.
• Variable naming schemes, coding formats, types of functions defined for particular uses, how files were accessed, database usage, documentation.
Object-Oriented approachBegin by analyzing the problem and identifying candidates for Objects. Example:
Die PairOfDice PigGame
PigPlayer
The variables and data structures of the traditional programming are replaced by 'state' variables within the classes.
Example: each player keeps track of his score, and dice know how to roll themselves.
Code Structure
Instead of code modules of 'helper' functions to manipulate the variables, each Object has it's own methods to implement behaviors of the Object.
Structure defined in diagrams…relationship between objects, and scenarios…how objects interact
The overall program structure will typically be defined in one of the methods in some top-level class...e.g. the PigGame class might have a controlling method called play.
Old style coding
int rollDie(void) {
return (int) (Math.random() * numFaces) + 1;
}
//Usage:
// int die; data structure
//die = rollDie();
Objects
• Objects have state and behavior– Example: String for example: "this is a
String object"– State is usually hidden, accessed by
operations• state: the actual characters• operations:
length/toUpperCase/indexOf() etc
Figure 5.1 A String object (for “Java is fun”)
length () indexOf(‘a’)
toUpperCase() // other services
Figure 5.2 A String object (for “JAVA IS FUN”)
length () indexOf(‘a’)
toLowerCase() // other services
public char charAt(int index) character at the specified index
public int compareTo(String anotherString)
0 if equal to anotherStringnegative if lesspositive if greater
public boolean equals(Object anObject)
true for equal Strings
public int indexOf(char ch) index of first occurrence of ch
public int indexOf(char ch, int from)
index of first occurrence of chstarting at index from
public int indexOf(String str) index of first occurrence of str
public int indexOf(String str, int from)
index of first occurrence of strstarting at index from
public int length() string length
Figure 5.3 Selected String methods(1)
public String substring (int beginIndex, int endIndex)
new string with characters frombeginIndex to endIndex – 1
public String toLowerCase() returns a lowercase string
public String toUpperCase() returns an uppercase string
public String trim() removes leading and trailingwhitespaces
public static String valueOf(int i) creates a string from an int
public static String valueOf(double d)
creates a string from a double
Figure 5.3 Selected String methods(2)
Method Return value Description of return value
s.charAt(6) ‘e’ The character at position 6 is an ‘e.’
s.compareTo(“Toast”) negative integer The string referred to by s is alphabetically less than “Toast” so the return value is a negative integer.
s.equals(“Java is fun”) false The string referred to by s does not have the same characters as “Java is fun”
s.indexOf(‘e’) 6 The leftmost ‘e’ on the string occurs at index 6.
s.indexOf(‘e’,8) 15 The first occurrence of ‘e,’ starting from index 8, is at index 15.
s.indexOf(“us”) 10 The leftmost occurrence of “us” starts at index 10.
Figure 5.4 Examples of string methods(1)
Method Return value Description of return value
s.indexOf(“us”,11)
13 The first occurrence of “us”, starting from index 11, begins at index 13.
s.indexOf(“us”,15)
-1 There is no occurrence of “us” staring at index 15.
s.length() 27 This string contains 27 characters.
s.substring(13,24)
A new String with characters “use objects.”
The string “use objects.” starts at index 13 and continues up to index 24.
s.toLowerCase() A new String with characters “java let us use objects. ”
Returns a new string with all lowercase characters.
s.toUpperCase() A new String with characters “JAVA LET US USE OBJECTS. ”
Returns a new string with all uppercase characters.
s.trim() A new String with characters “Java lets us use objects.”
Returns a new string with leading and trailing blanks removed
Figure 5.4 Examples of string methods(2)
Object types vs Java Classes
Objects types are implemented using Java Classes.
Objects are then instances of a Java class.
Java Class
• instance variables - or fields
• Instance Methods - refer to a specific instance of the object class
Variables
Values vs. Reference
int x = 4;
//x corresponds to a location containing the value 4
String s = "this is a String object";
//s corresponds to a location containing a ref (or pointer) to the actual object.
Object variables
• A ref (or object variable) is null until it is instantiated, usually with the new operator.
Figure 5.5 Value vs. reference
4
x my String
“We want a big car”
a. x holds a value b. myString holds a reference
s t
s t
“soup” “fish”
“soup” “fish”
String s = “soup”, t = “fish”;
t = s;
Figure 5.7 Assignment of a string
Figure 5.11 The revised BankAccount class
BankAccount
balance: doubleBankAccount()
BankAccount(initialAmount: double)
getBalance(): double
Deposit(amount: double): void
withdraw(amount: double): void
Figure 5.13 myAccount refers to a new BankAccount
:BankAccount
Balance = 0.0
getBalance
Deposit
withdrawmyAccount
transactionsAcct class
balance
myAcct object
balance
yourAcct object
Figure 5.15 The difference between class and instance variables
aCustomer
Figure 5.17 A sequence diagram for a food order
aWaiter aCook
take order
make burger
serve soda
make fries
serve burger
serve fries
pay
aCustomer
Figure 5.18 A revised sequence diagram for a food order
aWaiter aCook
take order
make burger
serve soda
make fries
serve burger
serve fries
place order
take soda order
take fries order
done
pay
Figure 5.19 Fields for the Name, Address and Person class(1)
Name
private String first
private char initial
private String last
public Name(String f, String l)
public Name(String f, char i, String l)
public String toString()
Address
private String street
private String city
private String state
private String zip
public Address(String st, String cy, String se, String zp)
public String toString()
Figure 5.19 Fields for the Name, Address and Person class(2)
Person
private String id
private Name name
private Address address
public Person(String i, Name a, Address a)
public String getId()
public String toString()
Person
id: String
name: Name
address: Address
Name
first: String
initial: char
last: String
Address
id: String
name: Name
address: Address
zip: String
Figure 5.20 Composition: the Name, Address and Person class