Functions as Values
A weekend discount as a true/false flag means the total's code changes with every new deal; functions as values let the caller hand in the rule instead: a function stored in a variable, passed to another function, or made and returned by one, in C#, Java, Python, JavaScript and TypeScript.
Apprentice · OOP · C# · Java · Python · JavaScript · TypeScript · Updated
After this lesson you can
- Store a function in a variable and pass it to another function as a value
- Write a function that returns a new function, such as a discount made from a percentage
- Choose which building block fits a change: an interface, a subclass, a held object, or a function passed in
Key takeaways
- A flag argument (weekend: true) puts every rule inside the function, so each new rule edits it and adds another flag.
- In all five languages a function is a value: it can be stored in a variable, passed in, and handed back.
- A lambda or arrow function is a function written in one line, with no name, where it's needed.
- A function that makes and returns a function, such as percentOff(20), turns one rule into a family of rules.
- Pick the building block by the change: a promise for new kinds of things, a held object for parts, a function for a rule.
Before this: Delegation: Handing the Job On, whose rentals this lesson prices. This one uses only their prices.
On weekends, Pedal & Go takes 20% off. Next month marketing wants 30% off on holidays, and after that $5 off for members, and they'll keep inventing deals for as long as the shop is open. Each deal is a rule, and right now each rule lives inside the code that adds up the day. Every one of the "modern versions" in this course's pattern lessons depends on the idea that fixes this: a function is a value you can hand around, like a number or a string.
A flag for every deal
Here's the desk's total with the weekend rule built in. A flag argument, a true or false passed in, says whether to apply it:
List<int> prices = new List<int> { 20, 45 };
Console.WriteLine( quot;Weekday: ${Total(prices, false)}");
Console.WriteLine( quot;Weekend: ${Total(prices, true)}");
int Total(List<int> prices, bool weekend)
{
int total = 0;
foreach (int price in prices)
{
total += price;
}
if (weekend)
{
total = total * 80 / 100;
}
return total;
}
Weekday: $65
Weekend: $52
int total(List<Integer> prices, boolean weekend) {
int total = 0;
for (int price : prices) {
total += price;
}
if (weekend) {
total = total * 80 / 100;
}
return total;
}
void main() {
List<Integer> prices = List.of(20, 45);
IO.println("Weekday: quot; + total(prices, false));
IO.println("Weekend: quot; + total(prices, true));
}
Weekday: $65
Weekend: $52
def total(prices, weekend):
result = sum(prices)
if weekend:
result = result * 80 // 100
return result
prices = [20, 45]
print(f"Weekday: ${total(prices, False)}")
print(f"Weekend: ${total(prices, True)}")
Weekday: $65
Weekend: $52
function total(prices, weekend) {
let result = 0;
for (const price of prices) {
result += price;
}
if (weekend) {
result = Math.floor(result * 80 / 100);
}
return result;
}
const prices = [20, 45];
console.log(`Weekday: ${total(prices, false)}`);
console.log(`Weekend: ${total(prices, true)}`);
Weekday: $65
Weekend: $52
function total(prices: number[], weekend: boolean): number {
let result = 0;
for (const price of prices) {
result += price;
}
if (weekend) {
result = Math.floor(result * 80 / 100);
}
return result;
}
const prices = [20, 45];
console.log(`Weekday: ${total(prices, false)}`);
console.log(`Weekend: ${total(prices, true)}`);
Weekday: $65
Weekend: $52
It works for one deal. Now add the holiday: a second flag, Total(prices, false, true). Then members: Total(prices, false, false, true). Every new deal edits the total's code, adds a flag to every call, and makes the calls harder to read: what does true, false, true mean? The total's real job is adding up prices. Which deal applies is somebody else's decision, and it keeps changing.
Hand the rule in
At a grocery store's checkout, you don't explain this week's deal to the cashier. You hand over a coupon, and the register applies whatever rule is printed on it: a dollar off, two for one, 10% off. The cashier's job stays the same; the coupon carries the rule.
In all five of the course's languages, a function can be treated as a value: stored in a variable, passed to another function, kept in a list. A function you can pass around like that is called a first-class function. So the total can take the deal as a function, and call it:

Func<int, int> noDiscount = total => total;
Func<int, int> weekend = total => total * 80 / 100;
Func<int, int> member = total => total - 5;
List<int> prices = new List<int> { 20, 45 };
Console.WriteLine( quot;Weekday: ${Total(prices, noDiscount)}");
Console.WriteLine( quot;Weekend: ${Total(prices, weekend)}");
Console.WriteLine( quot;Member: ${Total(prices, member)}");
// The total adds up the prices, then hands the result to whatever deal it was given.
int Total(List<int> prices, Func<int, int> discount)
{
int total = 0;
foreach (int price in prices)
{
total += price;
}
return discount(total);
}
Weekday: $65
Weekend: $52
Member: $60
// The total adds up the prices, then hands the result to whatever deal it was given.
int total(List<Integer> prices, Function<Integer, Integer> discount) {
int total = 0;
for (int price : prices) {
total += price;
}
return discount.apply(total);
}
void main() {
Function<Integer, Integer> noDiscount = total -> total;
Function<Integer, Integer> weekend = total -> total * 80 / 100;
Function<Integer, Integer> member = total -> total - 5;
List<Integer> prices = List.of(20, 45);
IO.println("Weekday: quot; + total(prices, noDiscount));
IO.println("Weekend: quot; + total(prices, weekend));
IO.println("Member: quot; + total(prices, member));
}
Weekday: $65
Weekend: $52
Member: $60
def total(prices, discount):
"""Adds up the prices, then hands the result to whatever deal it was given."""
return discount(sum(prices))
no_discount = lambda result: result
weekend = lambda result: result * 80 // 100
member = lambda result: result - 5
prices = [20, 45]
print(f"Weekday: ${total(prices, no_discount)}")
print(f"Weekend: ${total(prices, weekend)}")
print(f"Member: ${total(prices, member)}")
Weekday: $65
Weekend: $52
Member: $60
// The total adds up the prices, then hands the result to whatever deal it was given.
function total(prices, discount) {
let result = 0;
for (const price of prices) {
result += price;
}
return discount(result);
}
const noDiscount = (result) => result;
const weekend = (result) => Math.floor(result * 80 / 100);
const member = (result) => result - 5;
const prices = [20, 45];
console.log(`Weekday: ${total(prices, noDiscount)}`);
console.log(`Weekend: ${total(prices, weekend)}`);
console.log(`Member: ${total(prices, member)}`);
Weekday: $65
Weekend: $52
Member: $60
type Discount = (total: number) => number;
// The total adds up the prices, then hands the result to whatever deal it was given.
function total(prices: number[], discount: Discount): number {
let result = 0;
for (const price of prices) {
result += price;
}
return discount(result);
}
const noDiscount: Discount = (result) => result;
const weekend: Discount = (result) => Math.floor(result * 80 / 100);
const member: Discount = (result) => result - 5;
const prices = [20, 45];
console.log(`Weekday: ${total(prices, noDiscount)}`);
console.log(`Weekend: ${total(prices, weekend)}`);
console.log(`Member: ${total(prices, member)}`);
Weekday: $65
Weekend: $52
Member: $60
The member deal is new, and the total didn't change to get it. Each deal is a small function with no name, written right where it's needed. That's a lambda (C#, Java and Python's word) or an arrow function (JavaScript and TypeScript's):
| Language | The weekend deal | Read it as | Its type |
|---|---|---|---|
| C# | total => total * 80 / 100 |
"total goes to total times 80 over 100" | Func<int, int>: takes an int, gives an int |
| Java | total -> total * 80 / 100 |
"total goes to…" | Function<Integer, Integer>, called with .apply(...) |
| Python | lambda result: result * 80 // 100 |
"a function of result that gives…" | no type needed |
| JavaScript | (result) => Math.floor(result * 80 / 100) |
"result goes to…" | no type needed |
| TypeScript | the same, with (total: number) => number as its type |
"result goes to…" | written once as type Discount |
A function that takes another function, like Total, is called a higher-order function. You've probably used some already: a list's sort that takes a comparison, or a button's click handler.
A function that makes functions
Holidays are 30% off, a clearance sale might be 50%, and writing a new lambda for each percentage repeats the same math. A function can also return a function. percentOff(20) hands back a weekend deal; percentOff(30), a holiday deal:
List<int> prices = new List<int> { 20, 45 };
Func<int, int> weekend = PercentOff(20);
Func<int, int> holiday = PercentOff(30);
Console.WriteLine( quot;Weekend (20% off): ${Total(prices, weekend)}");
Console.WriteLine( quot;Holiday (30% off): ${Total(prices, holiday)}");
// Makes a deal: a function that takes this many percent off a total.
Func<int, int> PercentOff(int percent)
{
return total => total * (100 - percent) / 100;
}
int Total(List<int> prices, Func<int, int> discount)
{
int total = 0;
foreach (int price in prices)
{
total += price;
}
return discount(total);
}
Weekend (20% off): $52
Holiday (30% off): $45
// Makes a deal: a function that takes this many percent off a total.
Function<Integer, Integer> percentOff(int percent) {
return total -> total * (100 - percent) / 100;
}
int total(List<Integer> prices, Function<Integer, Integer> discount) {
int total = 0;
for (int price : prices) {
total += price;
}
return discount.apply(total);
}
void main() {
List<Integer> prices = List.of(20, 45);
Function<Integer, Integer> weekend = percentOff(20);
Function<Integer, Integer> holiday = percentOff(30);
IO.println("Weekend (20% off): quot; + total(prices, weekend));
IO.println("Holiday (30% off): quot; + total(prices, holiday));
}
Weekend (20% off): $52
Holiday (30% off): $45
def percent_off(percent):
"""Makes a deal: a function that takes this many percent off a total."""
return lambda result: result * (100 - percent) // 100
def total(prices, discount):
return discount(sum(prices))
prices = [20, 45]
weekend = percent_off(20)
holiday = percent_off(30)
print(f"Weekend (20% off): ${total(prices, weekend)}")
print(f"Holiday (30% off): ${total(prices, holiday)}")
Weekend (20% off): $52
Holiday (30% off): $45
// Makes a deal: a function that takes this many percent off a total.
function percentOff(percent) {
return (result) => Math.floor(result * (100 - percent) / 100);
}
function total(prices, discount) {
let result = 0;
for (const price of prices) {
result += price;
}
return discount(result);
}
const prices = [20, 45];
const weekend = percentOff(20);
const holiday = percentOff(30);
console.log(`Weekend (20% off): ${total(prices, weekend)}`);
console.log(`Holiday (30% off): ${total(prices, holiday)}`);
Weekend (20% off): $52
Holiday (30% off): $45
type Discount = (total: number) => number;
// Makes a deal: a function that takes this many percent off a total.
function percentOff(percent: number): Discount {
return (result) => Math.floor(result * (100 - percent) / 100);
}
function total(prices: number[], discount: Discount): number {
let result = 0;
for (const price of prices) {
result += price;
}
return discount(result);
}
const prices = [20, 45];
const weekend = percentOff(20);
const holiday = percentOff(30);
console.log(`Weekend (20% off): ${total(prices, weekend)}`);
console.log(`Holiday (30% off): ${total(prices, holiday)}`);
Weekend (20% off): $52
Holiday (30% off): $45
The returned function remembers the percent it was made with, even after percentOff has finished: weekend always takes 20% off. A function that remembers values from where it was made is called a closure. Money here stays in whole dollars, rounded down, so 30% off $65 is $45: whole-number division in C# and Java, // in Python, Math.floor in JavaScript and TypeScript.
Which building block?
This chapter has handed you five building blocks, and every pattern in the course is made of them. Each fits a different kind of change:
| When the change is… | Reach for | Example from the rental desk |
|---|---|---|
| new kinds of things that do the same job | an interface, and polymorphism | bikes, e-bikes, scooters, all Rentable |
| a more particular kind of something that really is one | a subclass | an e-bike is a bike |
| a part a thing has | a held object (composition) | a bike has a code lock |
| a job that belongs to a part | delegation | a rental hands the vehicle's price to the vehicle |
| a rule that keeps changing | a function passed in | this week's discount |
Try it. Add a clearance sale, percentOff(50), and print its total. It should be $32, and nothing else changes.
Check yourself
2 questions to try on the lesson page.
So what
When a rule keeps changing, don't build it in behind a flag: hand it in as a function, and the code that uses it never has to change for the next one.