Programming Search⌘K

Techniquecore

Combine functions into class

Also called group functions into a class.

Turn a group of functions that all take the same data into a class that holds the data, so that the shared context is explicit and the calls get shorter.

Family
refactoring
Intent
Make the data that several functions share into the state of one class, and the functions into its methods.

Purpose

A program often has a group of functions that each take the same record as their first argument: volume(parcel), chargeableWeight(parcel), shippingCost(parcel). The record is the common context of the group, but nothing in the code says so. Each caller passes the record again, and each reader must find the functions in the files where they happen to live.

Combine functions into class makes the record the state of a class and the functions its methods. The catalogue card shows base(aReading), taxableCharge(aReading) and calculateBaseCharge(aReading) becoming the methods base(), taxableCharge() and calculateBaseCharge() of a class Reading.1 The calls lose an argument, the group has one home, and the object can be passed to other parts of the program as one thing.2

The class is also a place for the logic that each caller wrote for itself. If three callers each computed the volume, that computation can become one more method.

Steps

  1. Run the tests and see them pass.
  2. Put the common data behind a class. If it is a record, Encapsulate Record does this; the class starts with the data and its accessors.2
  3. Test.
  4. Move each function that takes the record into the class, as a method. Remove the parameter, and change each caller to call the method. Test after each.
  5. Find logic in the callers that works on the data, extract it into a function, and move that function into the class too. Test after each.

Example

Three functions price a parcel, and a caller computes the volume for itself. After the refactoring the parcel is a class, and the volume is a method that every caller shares.

import assert from "node:assert/strict";

// Before: functions that each take the parcel record.
const DIVISOR = 5000; // cm^3 per kg of volumetric weight
function chargeableWeight(p) {
  const volume = p.length * p.width * p.height; // the caller computes it
  return Math.max(p.weightKg, volume / DIVISOR);
}
function shippingCost(p, ratePerKg) {
  return Math.ceil(chargeableWeight(p)) * ratePerKg;
}

// After: the data and the functions in one class.
class Parcel {
  #length; #width; #height; #weightKg;
  constructor({ length, width, height, weightKg }) {
    this.#length = length;
    this.#width = width;
    this.#height = height;
    this.#weightKg = weightKg;
  }
  get volume() { return this.#length * this.#width * this.#height; }
  get chargeableWeight() { return Math.max(this.#weightKg, this.volume / DIVISOR); }
  shippingCost(ratePerKg) { return Math.ceil(this.chargeableWeight) * ratePerKg; }
}

const records = [
  { length: 40, width: 30, height: 20, weightKg: 2 }, // light and bulky
  { length: 10, width: 10, height: 10, weightKg: 7 }, // small and heavy
];
for (const r of records) {
  assert.equal(new Parcel(r).shippingCost(3), shippingCost(r, 3));
}
assert.deepEqual(records.map((r) => new Parcel(r).shippingCost(3)), [15, 21]);
console.log("combine functions into class: tests pass");
Output
combine functions into class: tests pass

The calls now read parcel.shippingCost(3). The class holds the rule for the chargeable weight in one place, and a caller that needs the volume asks the parcel.

Language What the example shows
JavaScript the parcel functions as a class, as above
Python the same class, with functools.cached_property for a derived value
Go a struct with methods; the methods are the Go form of the class
PythonGitHub
import math
from functools import cached_property

DIVISOR = 5000  # cm^3 per kg of volumetric weight

# Before: functions that each take the parcel record.
def chargeable_weight(p):
    volume = p["length"] * p["width"] * p["height"]
    return max(p["weight_kg"], volume / DIVISOR)

def shipping_cost(p, rate_per_kg):
    return math.ceil(chargeable_weight(p)) * rate_per_kg

# After: one class. The parcel does not change, so a derived value
# can be computed once and kept with cached_property.
class Parcel:
    def __init__(self, length, width, height, weight_kg):
        self._dims = (length, width, height)
        self._weight_kg = weight_kg

    @cached_property
    def volume(self):
        return math.prod(self._dims)

    @property
    def chargeable_weight(self):
        return max(self._weight_kg, self.volume / DIVISOR)

    def shipping_cost(self, rate_per_kg):
        return math.ceil(self.chargeable_weight) * rate_per_kg

records = [
    {"length": 40, "width": 30, "height": 20, "weight_kg": 2},
    {"length": 10, "width": 10, "height": 10, "weight_kg": 7},
]
costs = [Parcel(**r).shipping_cost(3) for r in records]
assert costs == [shipping_cost(r, 3) for r in records] == [15, 21]
print(costs)
print("combine functions into class: tests pass")
Output
[15, 21]
combine functions into class: tests pass
package main

import (
	"fmt"
	"math"
)

const divisor = 5000.0 // cm^3 per kg of volumetric weight

type parcelRecord struct{ length, width, height, weightKg float64 }

// Before: functions that each take the record.
func chargeableWeight(p parcelRecord) float64 {
	return math.Max(p.weightKg, p.length*p.width*p.height/divisor)
}

func shippingCost(p parcelRecord, ratePerKg float64) float64 {
	return math.Ceil(chargeableWeight(p)) * ratePerKg
}

// After: in Go the class is a type with methods.
type Parcel struct{ length, width, height, weightKg float64 }

func (p Parcel) Volume() float64 { return p.length * p.width * p.height }

func (p Parcel) ChargeableWeight() float64 { return math.Max(p.weightKg, p.Volume()/divisor) }

func (p Parcel) ShippingCost(ratePerKg float64) float64 {
	return math.Ceil(p.ChargeableWeight()) * ratePerKg
}

func main() {
	records := []parcelRecord{{40, 30, 20, 2}, {10, 10, 10, 7}}
	for _, r := range records {
		p := Parcel(r) // the same fields, so a conversion works
		if p.ShippingCost(3) != shippingCost(r, 3) {
			panic("behaviour changed")
		}
		fmt.Println(p.ShippingCost(3))
	}
	fmt.Println("combine functions into class: tests pass")
}
Output
15
21
combine functions into class: tests pass

When to use

  • Several functions take the same data as their first argument. That shared argument is the state of a class that is not written yet.
  • Callers repeat logic on the data. The logic belongs with the data. This is the cure for Feature Envy in the callers, and for a Data Class with no behaviour.
  • The data is updated. If the source data can change, a class computes the derived values from the current state each time. The book prefers a class over Combine Functions into Transform in this case, because a transform copies values that go stale.2

If the data never changes and the program passes it as plain records, for example in a pipeline, a transform can fit better.2

Pitfalls

A class for its own sake. Two functions that share a parameter by chance do not need a class. The test is whether the functions belong to one concept that the program talks about.

A class that grows too much. Once the class exists, every function that touches the data tends to move in. Watch for Large Class, and split by responsibility when it grows.

The language does not need a class. In Go, methods on a struct do the work; in a functional language, a module with the type and its functions does the same job. The refactoring is about one home for the data and its operations, and the form follows the language.

Shared mutable state. If callers held the old record and changed it, they now hold an object whose state the methods read. Decide whether the class copies its input or keeps a reference.

Tools that do it

No tool in the table does the whole refactoring in one step. The tools do the parts.

Tool Languages What it automates
IntelliJ IDEA Java Extract Delegate, which lets you "extract some of the fields and methods of a class into a separate, newly created class", and Extract Method Object, which "moves method into a new class"3
VS Code TypeScript, JavaScript "Move to new file", which moves classes, functions and constants in the top-level scope to a file of their own4

The moves of each function into the class, and the change of each call from f(record) to record.f(), are the programmer's steps, and the tests check each one.

References

  1. Martin Fowler, Catalog of Refactorings, Combine Functions into Class, the entry
  2. Martin Fowler, Refactoring, Improving the Design of Existing Code, second edition, Addison-Wesley, 2018, Chapter 6, A First Set of Refactorings, Combine Functions into Class, motivation and mechanics; Combine Functions into Transform, motivation
  3. IntelliJ IDEA documentation, Extract into class refactorings, Extract delegate, Extract method object
  4. Visual Studio Code documentation, Refactoring TypeScript and JavaScript, the list of refactorings, the move of top-level code to a file of its own

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/XSMBY1/text.yaml