41
CS 112 Introduction to Programming (Spring 2012) Lecture #6: Static Methods and Decomposition Zhong Shao Department of Computer Science Yale University Office: 314 Watson http://flint.cs.yale.edu/cs112 Acknowledgements: some slides used in this class are taken directly or adapted from those accompanying the two textbooks: Introduction to Programming in Java: An Interdisciplinary Approach by Robert Sedgewick and Kevin Wayne and Building Java Programs: A Back to Basics Approach by Stuart Reges and Marty Stepp

CS 112 Introduction to Programming · Structured Algorithms ! Structured algorithm: Split into coherent tasks. 1 Preheat oven. Set oven to 375 degrees 2 Make the cookie batter. Mix

  • Upload
    others

  • View
    17

  • Download
    0

Embed Size (px)

Citation preview

Page 1: CS 112 Introduction to Programming · Structured Algorithms ! Structured algorithm: Split into coherent tasks. 1 Preheat oven. Set oven to 375 degrees 2 Make the cookie batter. Mix

CS 112 Introduction to Programming

(Spring 2012)

Lecture #6: Static Methods and Decomposition

Zhong Shao

Department of Computer Science

Yale University Office: 314 Watson

http://flint.cs.yale.edu/cs112

Acknowledgements: some slides used in this class are taken directly or adapted from those accompanying the two textbooks: Introduction to Programming in Java: An Interdisciplinary Approach by Robert Sedgewick and Kevin Wayne and Building Java Programs: A Back to Basics Approach by Stuart Reges and Marty Stepp

Page 2: CS 112 Introduction to Programming · Structured Algorithms ! Structured algorithm: Split into coherent tasks. 1 Preheat oven. Set oven to 375 degrees 2 Make the cookie batter. Mix

Recap: Structure of a Java program

public class <class name> { public static void main(String[] args) {

<statement>; <statement>; ... <statement>;

}

}

A class: -  has a name, defined in a file with same name

Convention we follow: capitalize each English word -  starts with {, and ends with } -  includes a group of methods

statement: -  a command to be executed -  end with ;

A static method (a.k.a. “function”): -  has a name

Convention we follow: lowercase first word, capital following

-  starts with {, and ends with } -  includes a group of statements

Page 3: CS 112 Introduction to Programming · Structured Algorithms ! Structured algorithm: Split into coherent tasks. 1 Preheat oven. Set oven to 375 degrees 2 Make the cookie batter. Mix

objects

static methods & classes

graphics, sound, and image I/O

arrays

conditionals and loops

Math text I/O

assignment statements primitive data types

any program you might want to write

build bigger programs and reuse code

A Foundation for Programming

Page 4: CS 112 Introduction to Programming · Structured Algorithms ! Structured algorithm: Split into coherent tasks. 1 Preheat oven. Set oven to 375 degrees 2 Make the cookie batter. Mix

Why Introduce “Static Methods”?

q  Algorithm: A list of steps for solving a problem.

q  An example algorithm: "Bake two batches of sugar cookies" 1.  Preheat oven temperature to 375F. 2.  Mix the dry ingredients. 3.  Cream the butter and sugar. 4.  Beat in the eggs. 5.  Stir in the dry ingredients. 6.  Set the timer for 8 min. 7.  Place 1st batch of cookies to oven. 8.  Allow the cookies to bake. 9.  Set the timer for 8 min. 10.  Place 2nd batch of cookies to oven. 11.  Allow the cookies to bake. 12.  Mix ingredients for frosting. 13.  Spread frosting and sprinkles.

Readability of the specification?

Page 5: CS 112 Introduction to Programming · Structured Algorithms ! Structured algorithm: Split into coherent tasks. 1 Preheat oven. Set oven to 375 degrees 2 Make the cookie batter. Mix

Problem of the Specification

q  Lack of structure: Many tiny steps; tough to remember. ❍  A human being typically can only manage seven (plus or

minus 2) pieces of information at one time

Page 6: CS 112 Introduction to Programming · Structured Algorithms ! Structured algorithm: Split into coherent tasks. 1 Preheat oven. Set oven to 375 degrees 2 Make the cookie batter. Mix

Problem of the Specification

q  Redundancy: unnecessary repeat

1.  Preheat oven temperature to 375F. 2.  Mix the dry ingredients. 3.  Cream the butter and sugar. 4.  Beat in the eggs. 5.  Stir in the dry ingredients. 6.  Set the timer for 8 min. 7.  Place the first batch of cookies into the oven. 8.  Allow the cookies to bake. 9.  Set the timer for 8 min. 10.  Place the second batch of cookies into the oven. 11.  Allow the cookies to bake. 12.  Mix ingredients for frosting. 13.  Spread frosting and sprinkles.

Page 7: CS 112 Introduction to Programming · Structured Algorithms ! Structured algorithm: Split into coherent tasks. 1 Preheat oven. Set oven to 375 degrees 2 Make the cookie batter. Mix

Structured Algorithms

q  Structured algorithm: Split into coherent tasks. 1 Preheat oven. ❍  Set oven to 375 degrees 2 Make the cookie batter. ❍  Mix the dry ingredients. ❍  Cream the butter and sugar. ❍  Beat in the eggs. ❍  Stir in the dry ingredients.

3 Bake the cookies. ❍  Set the timer for 8 min. ❍  Place the cookies into the oven. ❍  Allow the cookies to bake.

4 Add frosting and sprinkles. ❍  Mix the ingredients for the frosting. ❍  Spread frosting and sprinkles onto the cookies.

Page 8: CS 112 Introduction to Programming · Structured Algorithms ! Structured algorithm: Split into coherent tasks. 1 Preheat oven. Set oven to 375 degrees 2 Make the cookie batter. Mix

Structured Algorithms

q  Structured algorithm provides abstraction (hide/ignore the right details at the right time) 1 Preheat oven. ❍  Set oven to 375 degrees 2 Make the cookie batter. ❍  Mix the dry ingredients. ❍  Cream the butter and sugar. ❍  Beat in the eggs. ❍  Stir in the dry ingredients.

3 Bake the cookies. ❍  Set the timer. ❍  Place the cookies into the oven. ❍  Allow the cookies to bake.

4 Add frosting and sprinkles. ❍  Mix the ingredients for the frosting. ❍  Spread frosting and sprinkles onto the cookies.

Page 9: CS 112 Introduction to Programming · Structured Algorithms ! Structured algorithm: Split into coherent tasks. 1 Preheat oven. Set oven to 375 degrees 2 Make the cookie batter. Mix

Removing Redundancy

q  A well-structured algorithm can describe repeated tasks with less redundancy. 1 Preheat oven. 2 Make the cookie batter.

3a Bake the cookies (first batch). • 

3b Bake the cookies (second batch).

4 Decorate the cookies.

Page 10: CS 112 Introduction to Programming · Structured Algorithms ! Structured algorithm: Split into coherent tasks. 1 Preheat oven. Set oven to 375 degrees 2 Make the cookie batter. Mix

A Program with Redundancy

// This program displays a delicious recipe for baking cookies. public class BakeCookies { public static void main(String[] args) { System.out.println(“Preheat the oven."); System.out.println("Mix the dry ingredients."); System.out.println("Cream the butter and sugar."); System.out.println("Beat in the eggs."); System.out.println("Stir in the dry ingredients."); System.out.println("Set the timer."); System.out.println("Place a batch of cookies into the oven."); System.out.println("Allow the cookies to bake."); System.out.println("Set the timer."); System.out.println("Place a batch of cookies into the oven."); System.out.println("Allow the cookies to bake."); System.out.println("Mix ingredients for frosting."); System.out.println("Spread frosting and sprinkles."); } }

Issue: How to turn the program into structured specification?

Page 11: CS 112 Introduction to Programming · Structured Algorithms ! Structured algorithm: Split into coherent tasks. 1 Preheat oven. Set oven to 375 degrees 2 Make the cookie batter. Mix

Structured Algorithm?

// This program displays a delicious recipe for baking cookies. public class BakeCookies2 { public static void main(String[] args) { // Step 1: preheat oven System.out.println(“Preheat oven to 375F.");

// Step 2: Make the cookie batter. System.out.println("Mix the dry ingredients."); System.out.println("Cream the butter and sugar."); System.out.println("Beat in the eggs."); System.out.println("Stir in the dry ingredients.");

// Step 3a: Bake cookies (first batch). System.out.println("Set the timer for 8 min."); System.out.println("Place a batch of cookies into the oven."); System.out.println("Allow the cookies to bake.");

// Step 3b: Bake cookies (second batch). System.out.println("Set the timer for 8 min."); System.out.println("Place a batch of cookies into the oven."); System.out.println("Allow the cookies to bake.");

// Step 4: Decorate the cookies. System.out.println("Mix ingredients for frosting."); System.out.println("Spread frosting and sprinkles."); } }

Page 12: CS 112 Introduction to Programming · Structured Algorithms ! Structured algorithm: Split into coherent tasks. 1 Preheat oven. Set oven to 375 degrees 2 Make the cookie batter. Mix

Static Methods

q  Arrange statements into groups and give each group a name.

q  Each such named group of statements is a static method

q  Writing a static method is like adding a new command to Java.

class method A

statement statement statement

method B statement statement

method C statement statement statement

Page 13: CS 112 Introduction to Programming · Structured Algorithms ! Structured algorithm: Split into coherent tasks. 1 Preheat oven. Set oven to 375 degrees 2 Make the cookie batter. Mix

Static Methods

q  Benefits of methods ❍  denote the structure of a program ❍  allow code reuse to eliminate

redundancy

q  A main task of programming is procedural decomposition: dividing a problem into methods

class method A

statement statement statement

method B statement statement

method C statement statement statement

Page 14: CS 112 Introduction to Programming · Structured Algorithms ! Structured algorithm: Split into coherent tasks. 1 Preheat oven. Set oven to 375 degrees 2 Make the cookie batter. Mix

Gives your method a name so it can be executed q Syntax:

public static void <name>() { <statement>; <statement>; ... <statement>; }

q Example:

public static void printWarning() { System.out.println("This product causes cancer"); System.out.println("in lab rats and humans."); }

Declaring a Method

Page 15: CS 112 Introduction to Programming · Structured Algorithms ! Structured algorithm: Split into coherent tasks. 1 Preheat oven. Set oven to 375 degrees 2 Make the cookie batter. Mix

Calling a Method

Executes the method's code q  Syntax:

<name>();

❍  You can call the same method many times if you like.

q  Example:

printWarning();

❍  Output:

This product causes cancer in lab rats and humans.

Page 16: CS 112 Introduction to Programming · Structured Algorithms ! Structured algorithm: Split into coherent tasks. 1 Preheat oven. Set oven to 375 degrees 2 Make the cookie batter. Mix

Program with Static Method

public class FreshPrince { public static void main(String[] args) { rap(); // Calling (running) the rap method System.out.println(); rap(); // Calling the rap method again }

// This method prints the lyrics to my favorite song. public static void rap() { System.out.println("Now this is the story all about how"); System.out.println("My life got flipped turned upside-down"); } } Output:

Now this is the story all about how My life got flipped turned upside-down Now this is the story all about how My life got flipped turned upside-down

Page 17: CS 112 Introduction to Programming · Structured Algorithms ! Structured algorithm: Split into coherent tasks. 1 Preheat oven. Set oven to 375 degrees 2 Make the cookie batter. Mix

Design and Use Static Methods

1. Design the algorithm. ❍  Look at the structure, look for repeated commands

2. Declare (write down) the methods. ❍  Arrange statements into groups and give each group a

name.

3. Call (run) the methods. ❍  The program's main method executes the other methods

to perform the overall task.

Page 18: CS 112 Introduction to Programming · Structured Algorithms ! Structured algorithm: Split into coherent tasks. 1 Preheat oven. Set oven to 375 degrees 2 Make the cookie batter. Mix

Final Cookie Program // This program displays a delicious recipe for baking cookies. public class BakeCookies3 { public static void main(String[] args) { preheatOven(); makeBatter(); bake(); // 1st batch bake(); // 2nd batch decorate(); }

// Step 1: Preheat oven public static void preheatOven() { System.out.println(“Preheat Oven to 375F."); } // Step 2: Make the cake batter. public static void makeBatter() { System.out.println("Mix the dry ingredients."); System.out.println("Cream the butter and sugar."); System.out.println("Beat in the eggs."); System.out.println("Stir in the dry ingredients."); } // Step 3: Bake a batch of cookies. public static void bake() { System.out.println("Set the timer for 8 min."); System.out.println("Place a batch of cookies into the oven."); System.out.println("Allow the cookies to bake."); }

// Step 4: Decorate the cookies. public static void decorate() { System.out.println("Mix ingredients for frosting."); System.out.println("Spread frosting and sprinkles."); } }

Page 19: CS 112 Introduction to Programming · Structured Algorithms ! Structured algorithm: Split into coherent tasks. 1 Preheat oven. Set oven to 375 degrees 2 Make the cookie batter. Mix

q  Makes code easier to read by capturing the structure of the program ❍  main should be a good summary of the program

public static void main(String[] args) { }

Note: Longer code doesn’t necessarily mean worse code

Summary: Why Methods?

public static void main(String[] args) { } public static ... (...) { } public static ... (...) { }

Page 20: CS 112 Introduction to Programming · Structured Algorithms ! Structured algorithm: Split into coherent tasks. 1 Preheat oven. Set oven to 375 degrees 2 Make the cookie batter. Mix

q Eliminate redundancy public static void main(String[] args) {

}

Summary: Why Methods?

public static void main(String[] args) {

} public static ... (...) {

}

Page 21: CS 112 Introduction to Programming · Structured Algorithms ! Structured algorithm: Split into coherent tasks. 1 Preheat oven. Set oven to 375 degrees 2 Make the cookie batter. Mix

Summary: Static Methods

Java static methods (“functions”).   Takes zero or more input arguments.   Returns one output value or none.   Side effects (e.g., output to standard draw).

Applications.   Scientists use mathematical functions to calculate formulas.   Programmers use static methods to build modular programs.   You use static methods for both.

Examples.   Built-in functions: Math.random(), Math.abs(), Integer.parseInt().   Our I/O libraries: StdIn.readInt(), StdDraw.line(), StdAudio.play().   User-defined static methods: main().

more general than mathematical functions

Page 22: CS 112 Introduction to Programming · Structured Algorithms ! Structured algorithm: Split into coherent tasks. 1 Preheat oven. Set oven to 375 degrees 2 Make the cookie batter. Mix

Anatomy of a Java Static Method Java static methods. Easy to write your own.

f(x) = √x input

2.0 1.414213… output

Page 23: CS 112 Introduction to Programming · Structured Algorithms ! Structured algorithm: Split into coherent tasks. 1 Preheat oven. Set oven to 375 degrees 2 Make the cookie batter. Mix

More Examples

overloading

multiple arguments

Page 24: CS 112 Introduction to Programming · Structured Algorithms ! Structured algorithm: Split into coherent tasks. 1 Preheat oven. Set oven to 375 degrees 2 Make the cookie batter. Mix

q When a method A calls another method B, the program's execution...

❍  "jumps" into method B, executing its statements, then

❍  "jumps" back to method A at the point where the method was called.

Method Calling Flow

Page 25: CS 112 Introduction to Programming · Structured Algorithms ! Structured algorithm: Split into coherent tasks. 1 Preheat oven. Set oven to 375 degrees 2 Make the cookie batter. Mix

Methods Calling Methods

public class MethodsExample { public static void main(String[] args) { message1(); message2(); System.out.println("Done with main."); }

public static void message1() { System.out.println("This is message1."); }

public static void message2() { System.out.println("This is message2."); message1(); System.out.println("Done with message2."); } }

q  Output: This is message1. This is message2. This is message1. Done with message2. Done with main.

Page 26: CS 112 Introduction to Programming · Structured Algorithms ! Structured algorithm: Split into coherent tasks. 1 Preheat oven. Set oven to 375 degrees 2 Make the cookie batter. Mix

public class MethodsExample {

public static void main(String[] args) {

message1();

message2();

System.out.println("Done with main.");

}

...

}

public static void message1() { System.out.println("This is message1."); }

public static void message2() { System.out.println("This is message2."); message1(); System.out.println("Done with message2."); }

public static void message1() { System.out.println("This is message1."); }

Methods Calling Methods

Page 27: CS 112 Introduction to Programming · Structured Algorithms ! Structured algorithm: Split into coherent tasks. 1 Preheat oven. Set oven to 375 degrees 2 Make the cookie batter. Mix

27

Summary: Method “Control Flow” Key point. Static methods provide a new way to control the flow of execution. What happens when a function is called:   Control transfers to the function code.   Argument variables are assigned the values given in the call.   Function code is executed.   Return value is assigned in place of the function name in calling code.   Control transfers back to the calling code.

Note. This is known as "pass by value."

Page 28: CS 112 Introduction to Programming · Structured Algorithms ! Structured algorithm: Split into coherent tasks. 1 Preheat oven. Set oven to 375 degrees 2 Make the cookie batter. Mix

When NOT to use methods

q You should not create static methods for: ❍ Only blank lines. (Put blank printlns in main.) ❍ Unrelated or weakly related statements.

(A metric of method design is called coherence.)

Page 29: CS 112 Introduction to Programming · Structured Algorithms ! Structured algorithm: Split into coherent tasks. 1 Preheat oven. Set oven to 375 degrees 2 Make the cookie batter. Mix

Static Method Example

q Write a program to print these figures using methods. ______ / \ / \ \ / \______/ \ / \______/ +--------+ ______ / \ / \ | STOP | \ / \______/ ______ / \ / \ +--------+

Page 30: CS 112 Introduction to Programming · Structured Algorithms ! Structured algorithm: Split into coherent tasks. 1 Preheat oven. Set oven to 375 degrees 2 Make the cookie batter. Mix

Development Strategy

______ / \ / \ \ / \______/ \ / \______/ +--------+ ______ / \ / \ | STOP | \ / \______/ ______ / \ / \ +--------+

First version (unstructured):

Create an empty program and main method.

Copy the expected output into it, surrounding each line with System.out.println syntax.

Run it to verify the output.

Page 31: CS 112 Introduction to Programming · Structured Algorithms ! Structured algorithm: Split into coherent tasks. 1 Preheat oven. Set oven to 375 degrees 2 Make the cookie batter. Mix

Program version 1

public class Figures1 { public static void main(String[] args) { System.out.println(" ______"); System.out.println(" / \\"); System.out.println("/ \\"); System.out.println("\\ /"); System.out.println(" \\______/"); System.out.println(); System.out.println("\\ /"); System.out.println(" \\______/"); System.out.println("+--------+"); System.out.println(); System.out.println(" ______"); System.out.println(" / \\"); System.out.println("/ \\"); System.out.println("| STOP |"); System.out.println("\\ /"); System.out.println(" \\______/"); System.out.println(); System.out.println(" ______"); System.out.println(" / \\"); System.out.println("/ \\"); System.out.println("+--------+"); } }

Page 32: CS 112 Introduction to Programming · Structured Algorithms ! Structured algorithm: Split into coherent tasks. 1 Preheat oven. Set oven to 375 degrees 2 Make the cookie batter. Mix

Development Strategy 2

______ / \ / \ \ / \______/ \ / \______/ +--------+ ______ / \ / \ | STOP | \ / \______/ ______ / \ / \ +--------+

Second version (structured, with redundancy):

Identify the structure of the output.

Divide the main method into static methods based on this structure.

Page 33: CS 112 Introduction to Programming · Structured Algorithms ! Structured algorithm: Split into coherent tasks. 1 Preheat oven. Set oven to 375 degrees 2 Make the cookie batter. Mix

Output Structure

______ / \ / \ \ / \______/ \ / \______/ +--------+ ______ / \ / \ | STOP | \ / \______/ ______ / \ / \ +--------+

The structure of the output: initial "egg" figure

second "teacup" figure third "stop sign" figure

fourth "hat" figure

This structure can be represented by methods: egg

teaCup stopSign

hat

Page 34: CS 112 Introduction to Programming · Structured Algorithms ! Structured algorithm: Split into coherent tasks. 1 Preheat oven. Set oven to 375 degrees 2 Make the cookie batter. Mix

Program version 2

public class Figures2 { public static void main(String[] args) { egg(); teaCup(); stopSign(); hat(); } public static void egg() { System.out.println(" ______"); System.out.println(" / \\"); System.out.println("/ \\"); System.out.println("\\ /"); System.out.println(" \\______/"); System.out.println(); } public static void teaCup() { System.out.println("\\ /"); System.out.println(" \\______/"); System.out.println("+--------+"); System.out.println(); } ...

Page 35: CS 112 Introduction to Programming · Structured Algorithms ! Structured algorithm: Split into coherent tasks. 1 Preheat oven. Set oven to 375 degrees 2 Make the cookie batter. Mix

Program version 2, cont'd.

... public static void stopSign() { System.out.println(" ______"); System.out.println(" / \\"); System.out.println("/ \\"); System.out.println("| STOP |"); System.out.println("\\ /"); System.out.println(" \\______/"); System.out.println(); } public static void hat() { System.out.println(" ______"); System.out.println(" / \\"); System.out.println("/ \\"); System.out.println("+--------+"); } }

Page 36: CS 112 Introduction to Programming · Structured Algorithms ! Structured algorithm: Split into coherent tasks. 1 Preheat oven. Set oven to 375 degrees 2 Make the cookie batter. Mix

Development Strategy 3

______ / \ / \ \ / \______/ \ / \______/ +--------+ ______ / \ / \ | STOP | \ / \______/ ______ / \ / \ +--------+

Third version (structured, without redundancy):

Identify redundancy in the output, and create methods to eliminate as much as possible.

Add comments to the program.

Page 37: CS 112 Introduction to Programming · Structured Algorithms ! Structured algorithm: Split into coherent tasks. 1 Preheat oven. Set oven to 375 degrees 2 Make the cookie batter. Mix

Output redundancy

The redundancy in the output:

egg top: reused on stop sign, hat egg bottom: reused on teacup, stop sign

divider line: used on teacup, hat

This redundancy can be fixed by methods: eggTop

eggBottom line

______ / \ / \ \ / \______/ \ / \______/ +--------+ ______ / \ / \ | STOP | \ / \______/ ______ / \ / \ +--------+

Page 38: CS 112 Introduction to Programming · Structured Algorithms ! Structured algorithm: Split into coherent tasks. 1 Preheat oven. Set oven to 375 degrees 2 Make the cookie batter. Mix

Program version 3

// Suzy Student, CSE 138, Spring 2094 // Prints several figures, with methods for structure and

redundancy. public class Figures3 { public static void main(String[] args) { egg(); teaCup(); stopSign(); hat(); }

// Draws the top half of an an egg figure. public static void eggTop() { System.out.println(" ______"); System.out.println(" / \\"); System.out.println("/ \\"); }

// Draws the bottom half of an egg figure. public static void eggBottom() { System.out.println("\\ /"); System.out.println(" \\______/"); }

// Draws a complete egg figure. public static void egg() { eggTop(); eggBottom(); System.out.println(); }

...

Page 39: CS 112 Introduction to Programming · Structured Algorithms ! Structured algorithm: Split into coherent tasks. 1 Preheat oven. Set oven to 375 degrees 2 Make the cookie batter. Mix

Program version 3, cont'd.

...

// Draws a teacup figure. public static void teaCup() { eggBottom(); line(); System.out.println(); }

// Draws a stop sign figure. public static void stopSign() { eggTop(); System.out.println("| STOP |"); eggBottom(); System.out.println(); }

// Draws a figure that looks sort of like a hat. public static void hat() { eggTop(); line(); }

// Draws a line of dashes. public static void line() { System.out.println("+--------+"); } }

Page 40: CS 112 Introduction to Programming · Structured Algorithms ! Structured algorithm: Split into coherent tasks. 1 Preheat oven. Set oven to 375 degrees 2 Make the cookie batter. Mix

A Word about Style

q Structure your code properly q Eliminate redundant code q Use spaces judiciously and consistently q Indent properly q Follow the naming conventions q Use comments to describe code behavior

Page 41: CS 112 Introduction to Programming · Structured Algorithms ! Structured algorithm: Split into coherent tasks. 1 Preheat oven. Set oven to 375 degrees 2 Make the cookie batter. Mix

Why Style?

q  Programmers build on top of other’s code all the time. ❍  You shouldn’t waste time deciphering what a method

does.

q  You should spend time on thinking or coding. You should NOT be wasting time looking for that missing closing brace.

q So code with style!