CSCE 120: Learning To Code

Similar documents
Part I: Introduction to Functions

CSCE 120: Learning To Code

CSCE 120: Learning To Code

COMSC-051 Java Programming Part 1. Part-Time Instructor: Joenil Mistal

PIC 10A Objects/Classes

Chapter 4 Defining Classes I

Lecture 04 FUNCTIONS AND ARRAYS

Static Methods. Why use methods?

Module 10A Lecture - 20 What is a function? Why use functions Example: power (base, n)

Java Methods. Lecture 8 COP 3252 Summer May 23, 2017

6.096 Introduction to C++

CSCE 120: Learning To Code

Module 10: Imperative Programming, Modularization, and The Future

EVENT-DRIVEN PROGRAMMING

CS1 Lecture 4 Jan. 23, 2019

JAVASCRIPT AND JQUERY: AN INTRODUCTION (WEB PROGRAMMING, X452.1)

Chapter 7. Iteration. 7.1 Multiple assignment

Lecture 05: Methods. AITI Nigeria Summer 2012 University of Lagos.

Cpt S 122 Data Structures. Introduction to C++ Part II

4. Java Project Design, Input Methods

CS113: Lecture 4. Topics: Functions. Function Activation Records

static CS106L Spring 2009 Handout #21 May 12, 2009 Introduction

6.001 Notes: Section 6.1

JavaScript: Sort of a Big Deal,

Lecture 04 FUNCTIONS AND ARRAYS

CS1 Lecture 4 Jan. 24, 2018

Web Application Development

Functions. Lecture 6 COP 3014 Spring February 11, 2018

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 10: OCT. 6TH INSTRUCTOR: JIAYIN WANG

Functions. Systems Programming Concepts

Overview of the Ruby Language. By Ron Haley

Methods (Deitel chapter 6)

Methods (Deitel chapter 6)

Test Requirement Catalog. Generic Clues, Developer Version

5.6.1 The Special Variable this

CS112 Lecture: Repetition Statements

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #43. Multidimensional Arrays

CS390 Principles of Concurrency and Parallelism. Lecture Notes for Lecture #5 2/2/2012. Author: Jared Hall

Chapter 1 Getting Started

An interesting related problem is Buffon s Needle which was first proposed in the mid-1700 s.

CS112 Lecture: Loops

Chapter 3 - Functions

Object Oriented Methods : Deeper Look Lecture Three

Microsoft Excel Level 2

C Programming for Engineers Functions

CSE101-lec#12. Designing Structured Programs Introduction to Functions. Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU

Lecture 5: Methods CS2301

Software Engineering /48

Project 2: How Parentheses and the Order of Operations Impose Structure on Expressions

Functional abstraction. What is abstraction? Eating apples. Readings: HtDP, sections Language level: Intermediate Student With Lambda

Functional abstraction

Execution order. main()

Arrays Structured data Arrays What is an array?

6.001 Notes: Section 15.1

JavaScript CS 4640 Programming Languages for Web Applications

Case Study: Undefined Variables

Functions CMPE-013/L. Functions. Functions What is a function? Functions Remember Algebra Class? Gabriel Hugh Elkaim Winter 2014.

Fast Introduction to Object Oriented Programming and C++

>>> * *(25**0.16) *10*(25**0.16)

Recursion 1. Recursion is the process of defining something in terms of itself.

We have written lots of code so far It has all been inside of the main() method What about a big program? The main() method is going to get really

Intro. Scheme Basics. scm> 5 5. scm>

Chapter Fourteen Bonus Lessons: Algorithms and Efficiency

Department of Computer Science COMP The Programming Competency Test

CS110: PROGRAMMING LANGUAGE I

Software Design and Analysis for Engineers

Introducing Collaboration to Single User Applications

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 8/19/ Review. Here s a simple C++ program:

CSCE 120: Learning To Code

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 1/9/ Review. Here s a simple C++ program:

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

C Functions. 5.2 Program Modules in C

Shell CSCE 314 TAMU. Haskell Functions

Client Side JavaScript and AJAX

Pointers. A pointer is simply a reference to a variable/object. Compilers automatically generate code to store/retrieve variables from memory

JavaScript Basics. The Big Picture

Downloaded from Chapter 2. Functions

Chapter 4. Procedural Abstraction and Functions That Return a Value. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

What are the characteristics of Object Oriented programming language?

Princess Nourah bint Abdulrahman University. Computer Sciences Department

The return Statement

Container Vs. Definition Classes. Container Class

Object Oriented Programming in C#

Assignment II: Calculator Brain

Iteration. # a and b are now equal # a and b are no longer equal Multiple assignment

Software Design and Analysis for Engineers

Presented By Andrew Butt

Administration. Objects and Arrays. Objects. Agenda. What is an Object? What is a Class?

Variables and Typing

The design recipe. Readings: HtDP, sections 1-5. (ordering of topics is different in lectures, different examples will be used)

The compiler is spewing error messages.

Using Classes. GEEN163 Introduction to Computer Programming

Overview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017

Local definitions and lexical scope

Local definitions and lexical scope. Local definitions. Motivating local definitions. s(s a)(s b)(s c), where s = (a + b + c)/2.

Logistics. Final Exam on Friday at 3pm in CHEM 102

Design and Analysis of Algorithms Prof. Madhavan Mukund Chennai Mathematical Institute. Module 02 Lecture - 45 Memoization

(Refer Slide Time: 4:00)

CHAD Language Reference Manual

6.001 Notes: Section 17.5

Transcription:

CSCE 120: Learning To Code Module 9.0: Organizing Code I Introduction to Functions This module is designed to get you started working with functions which allow you to organize code into reusable units promoting proper procedural abstraction in your design. Introduction In programming languages, a function is a sequence of instructions (code) that is packaged into a unit. A function performs a specific task: given a number of inputs, it performs some operation (executes some code) and returns (outputs) a result. A function is usually defined by its signature: every function has a name (also called an identifier), a list of input parameters, and an output. A programming language function is very much like a mathematical function, f(x): x is the input, f is the name of the function, and when evaluated, it produces a value (output). Defining and using functions in a programming language offers many clear advantages. The most obvious advantage is that it allows you a way to organize code. By separating a program it into distinct units code is more organized and it is clearer what each piece of code does. This also facilitates top-down design: one way to approach a problem is to split it up into a series of subproblems until each subproblem is either trivial to deal with, or an existing, off-the-shelf solution already exists for it. Another advantage is that by putting code into functions, those functions can be reused in multiple places either in your program/project or even in other programs/projects. A prime example of this is the math library which has defined several useful mathematical functions and is used by thousands of programs across multiple different platforms. Placing code into functions also allows for better and easier testing. By isolating pieces of code, we can rigorously test those pieces of code by themselves without worrying about the larger program or contexts. 1

Finally, functions (sometimes called subroutines or procedures) facilitates procedural abstraction. Placing code into functions allows you to abstract the details of how the function computes its answer. As an example: consider the Math.sqrt() function: it may use some interpolation method, a Taylor series, or some other method entirely to compute the square root of a given number. However, by putting this functionality into a function, we, as programmers, do not need to concern ourselves about the details. Instead, we simply use the function, allowing us to focus on the larger issues at hand in our program. Functions in JavaScript JavaScript supports the ability to define and use functions. Defining Functions In JavaScript, we define a function using the keyword function. We also need to provide a name for the function and a list of its parameters (input values that will be passed to this function as arguments ). An example: 1 /** 2 * This function computes the annual percentage yield given 3 * an annual percentage rate (apr). 4 */ 5 function annualpercentageyield(apr) { 6 var apy = Math.pow((1 + (apr / 12)), 12) - 1; 7 return apy; 8 } The name of this function is annualpercentageyield and it takes one parameter. Function names follow the same rules as variables as well as the same conventions: your function names should describe what they do and should be lower camel-case. Function names, like variables, must be unique: you cannot have two different functions with the same name. Finally, declaring a function as above gives the function a global scope which means that any other piece of code will be aware of the function and will be able to use it. Parameters You can define as many parameters in your function as you like, even none. Multiple parameters are separated by a comma between the parentheses. The following example takes three parameters. Each parameter is like a variable and must follow the same naming rules and conventions. Inside the function you can use the parameters just like 2

variables in any expression that you write. 1 function getmonthlypayment(principle, apr, terms) { 2 var rate = (apr / 12); 3 return (principle * rate) / (1-Math.pow(1+rate, -terms)); 4 } The value passed to the function is the value that parameters take inside the function. This is known as pass-by-value. In detail, a copy of the variable s value passed to the function is provided to the function. You can change the value of a parameter, but it will have no effect on the variable that was passed to the function. An example: 1 function foo(a) { 2 a = 10; 3 return 20; 4 } 5... 6 var x = 5; 7 var y = foo(x); 8 /* at this point, x retains its value of 5; inside foo, only the 9 parameter was changed x and a are completely different 10 variables so changes to one will not affect the other 11 */ A slight exception to this is when you pass an object to the function. Changes to the object s fields will be reflected in the calling function. Another example: 1 function foo(s) { 2 s.firstname = "James"; 3 return; 4 } 5... 6 var student = { 7 "firstname": "John", 8 "lastname": "Student" 9 }; 10 foo(s); 11 //at this point, student.firstname has a value of James Return Values The purpose of a function is that you can provide it with inputs and it will give you an output; the result of its computation. This is known as the return value and can be specified using the return keyword. Returning a value immediately halts the execution of the function and returns the specified value. The value can be a variable, a constant, or even nothing at all (example: return; ). A function that does not return a value is 3

referred to as a void function. Calling Once a function is defined we can use it by calling it or invoking it. This is done by providing the function s name and any parameters. When calling a function, we sometimes refer to the parameters as arguments. Some examples: 1 var x; 2 x = getmonthlypayment(10000, 0.05, 60); 3... 4 var a = 10000, b = 0.05, c = 60; 5 x = getmonthlypayment(a, b, c); Optional Parameters In JavaScript it is possible to call a function and not pass some of the parameters. For example, the following function calls are all legal and will execute. 1 y = getmonthlypayment(a, b, c); 2 y = getmonthlypayment(a, b); 3 y = getmonthlypayment(a); 4 y = getmonthlypayment(); If you omit a parameter when invoking a function, the value of the parameter is treated as undefined inside the function. Undefined variables result in undefined results when used in expressions. This behavior is actually a feature: you can write functions where some of the parameters are optional. You can check whether or not a passed parameter is undefined by using something like the following. if(a === undefined) {... } And then provide default values or alternate behavior. We ve previously seen this behavior in jquery: many of the functions allow different behavior depending on how many arguments you provide it. For example.val() with no arguments, returns the value of the form element while providing an argument, say.val("0.00") sets the value of the web form element. A full example: 4

1 /** 2 * Computes the monthly payment given a principle amount, 3 * apr (default: 5%) and terms (default: 60 months) 4 */ 5 function getmonthlypayment(principle, apr, terms) { 6 if(apr === undefined) { 7 apr = 0.05; 8 } 9 if(terms === undefined) { 10 terms = 60; 11 } 12 var rate = (apr / 12); 13 return (principle * rate) / (1-Math.pow(1+rate, -terms)); 14 } In this example, we ve provided default values for the last two parameters, but the first value is required. Calls to this function will have the following behavior. 1 var x; 2 x = getmonthlypayment(10000, 0.05, 60); //188.71 3 x = getmonthlypayment(10000, 0.05); //188.71 4 x = getmonthlypayment(10000); //188.71 5 x = getmonthlypayment(); //undefined Functions as Members of Objects In all of the previous examples, the functions we defined were global. That is, the function could be seen and called by any other code block and could be called by any other piece of code. In JavaScript, functions can also be members of an object. An example: 1 var FinancialUtils = { 2 getmonthlypayment: function(principle, apr, terms) { 3 var rate = (apr / 12); 4 return (principle * rate) / (1-Math.pow(1+rate, -terms)); 5 }, 6 annualpercentageyield: function(apr) { 7 var apy = Math.pow((1 + (apr / 12)), 12) - 1; 8 return apy; 9 } 10 }; Note the difference in syntax here. The function identifier is placed first, followed by a colon and the function keyword. This should look familiar: this is exactly how functions in the standard Math library are organized. In the example above, the two functions are now members of FinancialUtils which is global. Invoking these functions now requires that you go through the FinancialUtils object. 5

1 var x = FinancialUtils.getMonthlyPayment(10000, 0.05, 60); 2 3 //the following is invalid: getmonthlypayment() does not exist 4 x = getmonthlypayment(10000, 0.05, 60); Callbacks Functions can call other functions. For example, the getmonthlypayment function calls the math library s exp function. By combining functions like this, we can create more complex programs. It also increases abstraction as we reuse pieces of code inside other pieces of code. As another example, consider the problem of computing the average of an array of numbers. We could write a function that sums up the elements of the array and then divides by its size. However, what if we already had a function to compute the sum of elements in an array? 1 function sum(arr) { 2 var sum = 0; 3 for(var i=0; i<arr.length; i++) { 4 sum += arr[i]; 5 } 6 return sum; 7 } 8 9 function ave(arr) { 10 var sum = 0; 11 for(var i=0; i<arr.length; i++) { 12 sum += arr[i]; 13 } 14 return (sum / arr.length); 15 } Having two separate functions with such closely related functionality is a waste of code: the first 4 lines are identical. Instead, we could save code and simplify this by reusing the sum function: 6

1 function sum(arr) { 2 var sum = 0; 3 for(var i=0; i<arr.length; i++) { 4 sum += arr[i]; 5 } 6 return sum; 7 } 8 9 function ave(arr) { 10 var sum = sum(arr); 11 return (sum / arr.length); 12 } Callbacks Not only can functions call other functions, but functions themselves can be passed to other functions as parameters. When passed as a parameter, a function is referred to as a callback. When passing a function A to another function B, the expectation is that B will call A (call it back) for its computation. As a motivating example, consider again the problem of computing the average of a list of numbers. Instead of a list of numbers, consider a list of objects representing courses. Suppose each course contained a count of the number of students enrolled in the course and we wanted to compute the average number of students per course. To do this we may write a function similar to the following. 1 function averageenrollment(courses) { 2 var sum = 0; 3 for(var i=0; i<arr.length; i++) { 4 sum += courses[i].count; 5 } 6 return (sum / courses.length); 7 } But this is essentially the same code as our original ave function with the exception of line 4. What if, instead, we wrote a general average function that is given both an array and a callback that can be used to compute the sum of the elements in an array. For example, 1 function average(arr, sumfunc) { 2 var sum = sumfunc(arr); 3 return (sum / arr.length); 4 } Here, the second argument is a callback (a function) that we invoke on the array to find the sum. This function is now generic: it can be invoked on an array of anything because the logic to sum elements is encapsulated inside the sumfunc function. Now that we 7

have a generalized average function, we can write a specialized function to compute the sum for an array of courses. 1 function sumofenrollments(courses) { 2 var sum = 0; 3 for(var i=0; i<courses.length; i++) { 4 sum += courses[i].count; 5 } 6 return sum; 7 } We can then invoke the general average function as follows: 1 var courses = [ 2 {name: "CSCE 120", count: 27}, 3 {name: "CSCE 220", count: 15}, 4 {name: "MATH 103", count: 89}]; 5 6 var x = average(courses, sumofenrollments); //43.66 We can now reuse average for any array of any type and we only need to worry about writing code to sum values. We could further generalize the sum array (or use the array function reduce() ). We will revisit these concepts when we explore how to organize data by sorting and searching. Anonymous Functions In the previous examples, all of our functions had identifiers. There is another way to define functions where the functions do not have a name. They are then known as anonymous functions since they have no name. There is nothing particularly special about doing this: strictly speaking, we don t need anonymous functions, but they allow us to use a software programming pattern whereby we can define and pass a function to another function all in the same line. As an example, consider the sumofenrollments function from before. It had only one use: to compute the sum of enrollments of an array of course objects. As such, the function didn t really have much use beyond creating it and handing it off to the average function. There is little reason for giving it a name if it is not going to be reused. Instead, we could have created it in-line when we called the average function: 8

1 var x = average(courses, function(courses) { 2 var sum = 0; 3 for(var i=0; i<courses.length; i++) { 4 sum += courses[i].count; 5 } 6 return sum; 7 }); In this example, we defined a function, but did not give it a name (we made it anonymous) and immediately passed it to the average function to be used as a callback. This is a common pattern that allows us to pass anonymous functions as callbacks. Asynchronous Computing Passing callbacks is not just a convenience: its a paradigm extensively used in asynchronous computing. The performance of many computing operations are bounded by input/output operations. That is, most of the time, the processor is sitting idle waiting for input/output to complete. By programming with callbacks, we can (potentially) resume normal execution without having to wait for I/O. For example, we could invoke a function that makes a connection to a remote server for data, then retrieves the data and processes it. This could potentially take a noticeable amount of time to a user especially if the network connection is slow and/or there is a lot of data to transfer. It would negatively impact the user experience (UX) if the rest of the page/application had to wait for the data to be transferred before anything else could be done. The user would essentially see the application as freezing while it waited for the data. Instead, we would like to continue normal operation without waiting for this process to complete. To do this, we provide the function a callback to use when it is done executing and we can continue with our normal operation. As we ve already seen, this pattern is used extensively in the jquery library. In particular, The.each() function takes a callback that it applies to each element in the set The ready() function takes a callback that is executed with the page is loaded and ready Pitfalls Understanding asynchronous operations can be difficult. In particular, problems can arise when two operations race each other. Consider the following jquery examples that attach an event to a button. The intention is that when the button is clicked, the first paragraph element is slowly hidden then reappears. 9

1 //example 1: 2 $("button").click(function(){ 3 $("#firstpara").hide("slow"); 4 $("#firstpara").show(); 5 }); 6 7 //example 2: 8 $("button").click(function(){ 9 $("#firstpara").hide("slow",function(){ 10 $("#firstpara").show(); 11 }); 12 }); The first example, however, will fail. When the hide() function is invoked, it takes some time (1.5 seconds) to execute. However, normal execution inside our function continues and the show function is called before the hide function completes making it have no effect. The second example correctly achieves our animation. What we really wanted was a certain sequence of events to fire, one after the other. To do this, we wrap our animation (callback) within another callback, etc. When the button is clicked, the first paragraph is hidden, but slowly. Only after the animation has been completed does the second callback execute and the paragraph is shown again. 10