Instructor: Prasun Dewan

Slides:



Advertisements
Similar presentations
Chapter 7: User-Defined Functions II
Advertisements

C OMP 110 S TATE Instructor: Jason Carter. 2 O UTLINE Instance Variables Procedures Properties Print Statements Println vs. Print Overloading.
C OMP 110 F UNCTIONS Instructor: Jason Carter. 2 O UTLINE Programmatic instantiation of objects Functions calling other functions Algorithm and stepwise.
C OMP 401 O BJECTS Instructor: Prasun Dewan 2 C OMPUTER VS. P ROGRAM M ODEL Processor Compiler Program (source code)
C OMP 110 O BJECTS Instructor: Jason Carter. 2 C OMPUTER VS. P ROGRAM M ODEL Processor Compiler Program (source code)
Introduction to Computers and Programming Lecture 4: Mathematical Operators New York University.
Midterm Exam 75 points 1 min per point Allocate time proportionate to points Closed book Chapters 1-5 (except char) PDF/PS with index and corrections coming.
Program Style Identifier Names Comments Named Constants Avoiding Code Repetition Giving Least Privilege Efficiency Interfaces.
1 Introduction to Software Engineering Lecture 42 – Communication Skills.
Object-based Programming Intuitive explanation Two concrete examples Calculators addition BMI Programming Environment.
ObjectEditor Prasun Dewan Comp 114. ObjectEditor Automatic user-interface generation. You only write computation code Separate object to do I/O Main just.
State Instance Variables Procedures Properties Print Statements Println Vs Print Overloading J++
More with Methods (parameters, reference vs. value, array processing) Corresponds with Chapters 5 and 6.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Programming Logic & Design First Edition by Tony Gaddis.
Chapter 06 (Part I) Functions and an Introduction to Recursion.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition, Fifth Edition Chapter 7: User-Defined Functions II.
Oct 15, 2007Sprenkle - CS1111 Objectives Creating your own functions.
SE: CHAPTER 7 Writing The Program
Introduction to programming in the Java programming language.
142 F -1 Functions chapter 3 of the text int main(void) { double x,y,z; … x = cube(y/3.0); … printf(“%f cubed is %f”,x,cube(x)); … return 0; } double cube(double.
Chapter 4: Subprograms Functions for Problem Solving Mr. Dave Clausen La Cañada High School.
Static Methods. 2 Objectives Look at how to build static (class) methods Study use of methods calling, parameters, returning values Contrast reference.
C OMP 110/401 E NCAPSULATION AND L EAST P RIVILEGE Instructor: Prasun Dewan.
Liang, Introduction to C++ Programming, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 6 Advanced Function Features.
Chapter 3: Developing Class Methods Object-Oriented Program Development Using Java: A Class-Centered Approach.
1 UMBC CMSC 104, Section Fall 2002 Functions, Part 1 of 3 Topics Top-down Design The Function Concept Using Predefined Functions Programmer-Defined.
CMSC 104, Section 301, Fall Lecture 18, 11/11/02 Functions, Part 1 of 3 Topics Using Predefined Functions Programmer-Defined Functions Using Input.
LECTURE 19 Subroutines and Parameter Passing. ABSTRACTION Recall: Abstraction is the process by which we can hide larger or more complex code fragments.
1 Sections 6.4 – 6.5 Methods and Variables Fundamentals of Java: AP Computer Science Essentials, 4th Edition Lambert / Osborne.
Copyright © 2012 Pearson Education, Inc. Chapter 4 Writing Classes : Review Java Software Solutions Foundations of Program Design Seventh Edition John.
 Pearson Education, Inc. All rights reserved Methods: A Deeper Look.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 4.
Object-Oriented Programming
Chapter 9: Value-Returning Functions
Programming Logic and Design Seventh Edition
Algorithms and Problem Solving
Chapter 6 - Functions modular programming general function format
Chapter 7: User-Defined Functions II
Reference: COS240 Syllabus
Chapter 2: Input, Processing, and Output
Methods Chapter 6.
Chapter 3: Using Methods, Classes, and Objects
About the Presentations
Functions CIS 40 – Introduction to Programming in Python
Introduction to UML: Unified Modeling Language
C++ for Engineers and Scientists Second Edition
Starting Out with Programming Logic & Design
METHODS AND BEHAVIORS AKEEL AHMED.
Chapter 6 Methods: A Deeper Look
Chapter 4 void Functions
VHDL Discussion Subprograms
Comp 110/401 Documentation: Comments
A First Book of ANSI C Fourth Edition
5. Functions Rocky K. C. Chang 30 October 2018
VHDL Discussion Subprograms
Chapter 9: Value-Returning Functions
Algorithms and Problem Solving
Starting Out with Programming Logic & Design
Defining Classes and Methods
Defining Classes and Methods
Chapter 2: Input, Processing, and Output
Predefined Functions Revisited
Classes, Objects and Methods
Review of Previous Lesson
Java Methods: A Deeper Look Academic 2019 Class: BIT23/BCS10 Chapter 06 Abdulaziz Yasin Nageye Faculty of Computing Java How to Program, 10/e 1 © Co py.
Chapter 10: Void Functions
Presentation transcript:

Instructor: Prasun Dewan Comp 110 Functions Instructor: Prasun Dewan

Prerequisite Objects

Outline Programmatic instantiation of objects Functions calling other functions Algorithm and stepwise refinement Code Reuse Programming Style Variables, Named Constants, Literals Comments and Identifier Names

General Purpose BMI Calculator Does not assume height or weight Specialized could know my height

BMI Calculator Specialized for an Individual’s Height Need to enter only weight weight Height is hard-coded into the program

A Solution public class AMyBMICalculator { public double calculateMyBMI(double weight) { }

A Solution (Edit) public class AMyBMICalculator { public double calculateMyBMI(double weight) { }

Relationship with ABMICalculator? A Solution public class AMyBMICalculator { public double calculateMyBMI(double weight) { return weight/ (1.94 * 1.94); } Relationship with ABMICalculator?

Customized vs. General Purpose public class AMyBMICalculator { public double calculateMyBMI(double weight) { return weight/ (1.94 * 1.94); } One vs. two parameters public class ABMICalculator { public double calculateBMI (double weight, double height) { return weight/ (height * height); } Basic formula is the same (can cut and paste)

Particularly important for complex code Should Reuse! public class AMyBMICalculator { public double calculateMyBMI(double weight) { return weight/ (1.94 * 1.94); } Should reuse code to avoid duplication of effort and errors such as: (weight)/1.94 public class ABMICalculator { public double calculateBMI (double weight, double height) { return weight/ (height * height); } Particularly important for complex code

How to Reuse ABMICalculator Create an instance of ABMICalculator Invoke the method calculateBMI() on this instance passing it my weight and my height as actual parameters The value returned by the method is my BMI

Interactive Execution of the Steps Create an instance of ABMICalculator Invoke the method calculateBMI() on this instance passing it my weight and my height as actual parameters The value returned by the method is my BMI

Programming The Steps Create an instance of ABMICalculator Invoke the method calculateBMI() on this instance passing it my weight and my height as actual parameters The value returned by the method is my BMI public class AMyBMICalculator { public double calculateMyBMI(double weight) { } return (new ABMICalculator()) .calculateBMI( ); weight, 1.94

Method Invocation Syntax (new ABMICalculator()).calculateBMI(weight, 1.94); Target Object Method Name Actual Parameters

Function Composition public class AMyBMICalculator { public double calculateMyBMI(double weight) { return (new ABMICalculator()).calculateBMI(weight,1.94); } The body of the calling function calls (invokes) other functions to do its job Passes the “buck” to the callee or called functions calculateMyBMI() calls calculateBMI() Supports reuse

Call Graphs calculateMyBMI(74.98) 19.92 19.92 calculateBMI(74.98,1.94)

Graphical Illustration of the CalculateMyBMI Call Class AMyBMICalculator Class ABMICalculator  instance of  AMyBMICalculator instance of public double calculateMyBMI(double weight) {  return (new ABMICalculator()) ABMICalculator .calculateBMI(weight, 1.94);  } public double calculateBMI(double weight, double height) { return weight/(height*height); } 

Mathematical Intuition Behind Function Invocation tan(x) = sin(x) / cos(x) tan(90) 1 sin(90) cos(90)

AverageBMICalculator Weight 1 Weight 2

A Solution public class AMyAverageBMICalculator { public double calculateMyAverageBMI(double weight1, double weight2) { }

A Solution (Edit) public class AMyAverageBMICalculator { public double calculateMyAverageBMI(double weight1, double weight2) { <edit here> }

A Solution public class AMyAverageBMICalculator { public double calculateMyAverageBMI(double weight1, double weight2) { return ((new ABMICalculator()).calculateBMI(weight1, 1.94) + (new ABMICalculator()).calculateBMI(weight2, 1.94))/2; } Creating a new instance of AMyAverageBMICalculator each time calculateBMI is to be called!

Interactive Equivalent Instance 1 Instance 2

A Better Interactive Approach Instance 1 ObjectEditor window identifies the appropriate instance. Need way to name objects in a program.

Naming Memory Locations Can name values in a program by using variables Each program value stored in a memory location Variable declarations name memory locations Have already seen variable declarations!

Formal Parameters as Variables public class AMyBMICalculator { public double calculateMyBMI(double weight) { return weight/ (1.94 * 1.94); } Formal parameters are special kinds of variables. weight is name of memory location that stores the actual parameter passed by caller

Internal Method Variables Like formal parameters are declared with type and name Name in subsequent code refers to value stored in memory location Declared in a method body rather than header Can be explicitly given initial values Which can be changed later Make program more efficient as an extra object is not instantiated public class AMyAverageBMICalculator { public double calculateMyAverageBMI(double weight1, double weight2) { ABMICalculator aBMICalculator = new ABMICalculator(); return (aBMICalculator .calculateBMI(weight1, 1.94) + aBMICalculator.calculateBMI(weight2, 1.94))/2; }

More Use of Variables bmi1 and bmi2 name memory locations that store the two intermediate results Not really needed to make programs efficient public class AMyAverageBMICalculator { public double calculateMyAverageBMI(double weight1, double weight2) { ABMICalculator aBMICalculator = new ABMICalculator(); double bmi1 = aBMICalculator.calculateBMI(weight1, 1.94); double bmi2 = aBMICalculator.calculateBMI(weight2, 1.94); return (bmi1 + bmi2)/2; }

Which is Better? First solution is more concise public class AMyAverageBMICalculator { public double calculateMyAverageBMI(double weight1, double weight2) { AMyBMICalculator aMyBMICalculator = new AMyBMICalculator(); return (aMyBMICalculator.calculateMyBMI(weight1) + aMyBMICalculator.calculateMyBMI(weight2)) / 2; } public class AMyAverageBMICalculator { public double calculateMyAverageBMI(double weight1, double weight2) { AMyBMICalculator aMyBMICalculator = new AMyBMICalculator(); double bmi1 = aMyBMICalculator.calculateMyBMI(weight1); double bmi2 = aMyBMICalculator.calculateMyBMI(weight2); return (bmi1 + bmi2) / 2; } First solution is more concise Second solution separates various steps, giving names to each intermediate calculated value Hard to argue between them Second solution makes it easier to single-step through code

Programming Style More than one solution to a problem Some solutions arguably “better” than others E.g. one solution allows reuse other does not. Programming style determines which solution is chosen Style as important as correctness Good style often promotes correctness

Style Rules Elements of Style Support code reuse Other style rules?

A mysterious (at least to some) number in code Improving the Style public class AMyBMICalculatorWithReuse { public double calculateMyBMI(double weight) { return (new ABMICalculator()).calculateBMI(weight,1.94); } A Magic Number A mysterious (at least to some) number in code

Named Constants Like variables have type, name and value public class AMyBMICalculator { public double calculateMyBMI(double weight) { final double MY_HEIGHT = 1.94; return (new ABMICalculator()).calculateBMI(weight, MY_HEIGHT); } Like variables have type, name and value They must have an initial value Initial value of a variable is optional The final keyword says value cannot be changed later The name is all caps by convention

Named Constants, Literals, Constants & Variables public class AMyBMICalculator { public double calculateMyBMI(double weight) { final double MY_HEIGHT = 1.94; return (new ABMICalculator()).calculateBMI(weight, MY_HEIGHT); } Literal Variable Constant Named Constant Literal A value directly specified in the program Constant A fixed value Can be literal or named constant Variable A potentially variable value

Pound Inch BMI Calculator

Pound Inch BMI Calculator Weight in pounds Height in inches

Steps for Reusing ABMICalculator

Steps for Reusing ABMICalculator

Steps for Reusing ABMICalculator Calculate weight in Kgs from weight in Pounds Calculate height in Metres from height in inches Call calculateBMI() of ABMICalculator with these values Return the value returned by this call

A Solution public class APoundInchBMICalculator { public double calculateBMI( double weightInLbs, double heightInInches) { }

A Solution (Edit) public class APoundInchBMICalculator { public double calculateBMI( double weightInLbs, double heightInInches) { }

A Solution (Edit) public class APoundInchBMICalculator { public double calculateBMI( double weightInLbs, double heightInInches) { return (new ABMICalculator()).calculateBMI( weightInLbs/2.2, heightInInches*2.54/100); }

Algorithm Description of solution to a problem. Can be in any “language” graphical natural or programming language natural + programming language (pseudo code) Can describe solution to various levels of detail

Real-World Algorithm Enter Class Distribute handouts Set up laptop projection. Revise topics learnt in the last class. Teach today’s topics. Leave Class

Algorithm for Reusing ABMICalculator Calculate weight in Kgs from weight in Pounds Calculate height in Metres from height in inches Call calculateBMI() of ABMICalculator with these values Return the value returned by this call

2nd Level Algorithm Calculate weight in kgs from weight in Pounds Divide weight in Pounds by 2.2 Calculate height in Meters from height in inches Calculate height in centimeters from height in inches and divide it by 100 to get height in meters Call calcuateBMI() of ABMICalculator with these values Return the value returned by this call

3rd Level Algorithm Calculate weight in kgs from weight in Pounds Divide weight in Pounds by 2.2 Calculate height in Metres from height in inches Calculate height in centimetres from height in inches and divide it by 100 to get height in metres Multiply height in Inches by 2.54 to get height in centimetres Call calcuateBMI() of ABMICalculator with these values Return the value returned by this call

Stepwise Refinement Natural Language Algorithm Calculate weight in Kgs from weight in Pounds Calculate height in Meters from height in inches Call calculateBMI() of ABMICalculator with these values Return the value returned by this call Programming Language Algorithm public class APoundInchBMICalculator () { public double calculateBMI( double weightInLbs, double heightInInches) { return (new ABMICalculator()).calculateBMI( weightInLbs/2.2, heightInInches*2.54/100); }

Style Problems Unlike algorithm, code is single-level public class APoundInchBMICalculator { public double calculateBMI( double weightInLbs, double heightInInches) { return (new ABMICalculator()).calculateBMI( weightInLbs/2.2, heightInInches*2.54/100); } Unlike algorithm, code is single-level By defining functions for each algorithm level we can create multi-level code Multi-level code would be more reusable as there are more parts that can be used independently

Multi-Level Code public class APoundInchBMICalculator { public double calculateBMI( double weightInLbs, double heightInInches) { return (new ABMICalculator()).calculateBMI( toKgs(weightInLbs), toMetres(heightInInches)); } public double toMetres(double heightInInches) { ??? public double toKgs(double weightInLbs) { Can be reused in contexts other than BMI (designing for reuse). Design for Reuse vs. Reusing available code

Multi-Level Code (Edit) public class APoundInchBMICalculator { public double calculateBMI( double weightInLbs, double heightInInches) { return (new ABMICalculator()).calculateBMI( toKgs(weightInLbs), toMetres(heightInInches)); } public double toMetres(double heightInInches) { ??? public double toKgs(double weightInLbs) {

Multi-Level Code public class APoundInchBMICalculator { public double calculateBMI( double weightInLbs, double heightInInches) { return (new ABMICalculator()).calculateBMI( toKgs(weightInLbs), toMetres(heightInInches)); } public double toMetres(double heightInInches) { return toCentiMetres(heightInInches)/100; public double toCentiMetres(double heightInInches) { return heightInInches*2.54; public double toKgs(double weightInLbs) { return weightInLbs/2.2;

Multi-Level Call Graph 23.72 (new ABMICalculator). calculateBMI(75,1.77) calculateBMI(165,70) 1.778 23.72 75 toMetres (70) toKgs (165) 177.8 toCentiMetres (70)

External vs. Internal Method Invocation Syntax (new ABMICalculator()).calculateBMI(75,1.77)); Actual Parameters Method Name Target Object toKgs(165);

External vs. Internal Method Invocation Syntax External Method Call Caller (calling method) and callee (called method) belong to different objects calculateBMI() of APoundInchBMICalculator instance calls calculateBMI() of ABMICalculator instance Internal Method Call Caller and callee methods belong to same object calculateBMI() of APoundInchBMICalculator instance calls toKgs() of APoundInchBMICalculator instance Target object optional in internal method call Target object needed because multiple objects may have the same method When target object omitted caller’s object is target object

Reusability Can be reused in other classes public class APoundInchBMICalculator { public double calculateBMI( double weightInLbs, double heightInInches) { return (new ABMICalculator()).calculateBMI( toKgs(weightInLbs), toMetres(heightInInches)); } public double toMetres(double heightInInches) { return toCentiMetres(heightInInches)/100; public double toCentiMetres(double heightInInches) { return heightInInches*2.54; public double toKgs(double weightInLbs) { return weightInLbs/2.2; Can be reused in other classes (new APoundInchBMICalculator()).toCentiMetres(70) (new APoundInchBMICalculator()).toMetres(70) (new APoundInchBMICalculator()).toKgs(165)

Lack of Reusability A single method implements all three conversions public class APoundInchBMICalculator { public double calculateBMI( double weightInLbs, double heightInInches) { return (new ABMICalculator()).calculateBMI( weightInLbs/2.2, heightInInches*2.54/100); } A single method implements all three conversions Cannot reuse each conversion independent of BMI calculation

Magic Numbers Revisited public class APoundInchBMICalculator { public double calculateBMI( double weightInLbs, double heightInInches) { return (new ABMICalculator()).calculateBMI( toKgs(weightInLbs), toMetres(heightInInches)); } public double toMetres(double heightInInches) { return toCentiMetres(heightInInches)/100; public double toCentiMetres(double heightInInches) { return heightInInches*2.54; public double toKgs(double weightInLbs) { return weightInLbs/2.2; magic numbers?

“Well-Known” vs. “Obscure” Number Well-Known Number (Natural constant) weightInLbs/2.2 Obscure Number (new ABMICalculator). calculateBMI(74, 1.77);

What is a Magic Number? Obscure number is a magic number Well-known number is not A number defined by law of nature e.g number of centimeters in an inch Π What is well-known depends on the audience e.g. number of centimeters in an inch Numbers defined by law of nature may not be considered magic numbers All other numbers should be considered magic numbers

Removing All Potentially Magic Numbers public class APoundInchBMICalculator { public double calculateBMI( double weightInLbs, double heightInInches) { return (new ABMICalculator()).calculateBMI( toKgs(weightInLbs), toMetres(heightInInches)); } public double toMetres(double heightInInches) { final double CMS_IN_METRES = 100; return toCentiMetres(heightInInches)/ CMS_IN_METRES; public double toCentiMetres(double heightInInches) { final double CMS_IN_INCH = 2.54; return heightInInches* CMS_IN_INCH; public double toKgs(double weightInLbs) { final double LBS_IN_KG = 2.2; return weightInLbs/LBS_IN_KG;