I'll Be Backend
Code smells · Go

Long parameter list: introduce a parameter object

Group the values that travel together, so a new one stops touching every signature.

14 steps5 chapters~6 min at 1.25×#long parameter list#data clump#parameter object#method signatures
The lesson plays right here. Pause anywhere, step back, or jump to a step below. Watch the Go video on YouTube Code on GitHub

Watch the narrated video

Every step

Problem

Steps 1–4

Refactor

Steps 5–9

Payoff

Steps 10–11

Go bonus

Step 12

Recap

Steps 13–14

The code: before and after

Before

type ShippingService struct {
	rates RateTable
}

func (s ShippingService) Quote(
	fromPostal, fromCountry, toPostal, toCountry string,
	weightKg, lengthCm, widthCm, heightCm float64,
	express bool,
) ShippingQuote {
	price := s.price(fromCountry, toCountry,
		weightKg, lengthCm, widthCm, heightCm, express)
	return ShippingQuote{fromPostal, toPostal, price}
}

func (s ShippingService) price(
	fromCountry, toCountry string,
	weightKg, lengthCm, widthCm, heightCm float64,
	express bool,
) float64 {
	volumetricKg := lengthCm * widthCm * heightCm / 5000
	cost := s.rates.PerKg(fromCountry, toCountry) *
		max(weightKg, volumetricKg)
	if express {
		cost *= 1.5
	}
	return cost
}

const (
	warehousePostal  = "10115"
	warehouseCountry = "DE"
)

type Checkout struct {
	shipping ShippingService
}

func (c Checkout) ShippingFor(cart Cart, customer Customer) ShippingQuote {
	return c.shipping.Quote(warehousePostal, warehouseCountry,
		customer.PostalCode, customer.Country,
		cart.WeightKg, cart.LengthCm, cart.WidthCm, cart.HeightCm,
		cart.Express)
}

After

type Address struct {
	Postal, Country string
}

type Parcel struct {
	WeightKg                    float64
	LengthCm, WidthCm, HeightCm float64
	Fragile                     bool
}

func (p Parcel) billableKg() float64 {
	volumetricKg :=
		p.LengthCm * p.WidthCm * p.HeightCm / 5000
	return max(p.WeightKg, volumetricKg)
}

type ShippingService struct {
	rates RateTable
}

func (s ShippingService) Quote(
	from, to Address, parcel Parcel, express bool,
) ShippingQuote {
	price := s.price(from, to, parcel, express)
	return ShippingQuote{from.Postal, to.Postal, price}
}

func (s ShippingService) price(
	from, to Address, parcel Parcel, express bool,
) float64 {
	cost := s.rates.PerKg(from.Country, to.Country) *
		parcel.billableKg()
	if parcel.Fragile {
		cost *= 1.2
	}
	if express {
		cost *= 1.5
	}
	return cost
}

const (
	warehousePostal  = "10115"
	warehouseCountry = "DE"
)

type Checkout struct {
	shipping ShippingService
}

func (c Checkout) ShippingFor(cart Cart, customer Customer) ShippingQuote {
	from := Address{warehousePostal, warehouseCountry}
	to := Address{customer.PostalCode, customer.Country}
	parcel := Parcel{
		WeightKg: cart.WeightKg,
		LengthCm: cart.LengthCm,
		WidthCm:  cart.WidthCm,
		HeightCm: cart.HeightCm,
		Fragile:  cart.Fragile,
	}
	return c.shipping.Quote(from, to, parcel, cart.Express)
}

Transcript, step by step

Problem

Step 1: A quote with nine parameters Before

At checkout, this method asks the shipping service for a quote. It passes the warehouse address from two constants, then the customer's address, then five values from the cart. The quote method takes all nine, and hands seven of them on to the price method. Price works out a volumetric weight from the box size, charges for whichever weight is larger, and adds half again for express.

Step 2: One flag, five edits Code smell

The carrier now charges twenty percent more for fragile parcels. Price needs a fragile flag, so the quote method, the call inside it and the checkout call all have to carry one there. A long parameter list is a method that takes so many values that every caller must line them up in the right order. You can see it here in the quote signature, here in the price signature, here in the call inside quote, and here in the checkout call. Quote uses two of its ten values itself, and the other eight pass straight through to price.

Step 3: Two bools in one group Code smell

One new value cost four edits to signatures and calls before we reached the one check that uses it. And express and fragile now sit side by side, two booleans in one group in both signatures. If someone swaps them at the checkout call, the code still compiles, and the customer pays the wrong surcharge.

Step 4: Back it out, then group Plan

Let's back that change out and refactor first. Look at which values travel together, because the same groups show up in every list. The origin postal code and country always come as a pair, so do the destination's, and so do the weight and the three box sizes. A group like that is called a data clump, and Introduce Parameter Object turns each clump into one small struct. We'll do it one clump at a time, and after each step the code compiles and the price comes out the same.

Refactor

Step 5: The origin becomes an Address Introduce Parameter Object

The origin comes first, so we add an Address struct with a postal code and a country. Quote and price now take one Address called from, where they took two strings. Quote reads the postal code from it, and price reads the country. Checkout builds that address from the two warehouse constants.

Step 6: The destination is an Address too Introduce Parameter Object

The destination is the same kind of clump, so it reuses the same Address type. Both methods take from and to now, and the quote reads both postal codes off them. Checkout builds the second address from the customer.

Step 7: Four floats become a Parcel Introduce Parameter Object

The last clump is the weight and the three box sizes, so they become a Parcel struct. Four floats leave both signatures, and quote takes four parameters where it took nine. The call between them fits on one line now, and checkout builds the parcel from the cart. Price now reaches into the parcel four times to work out the weight it charges for.

Step 8: Name the weight rule Extract Method

That weight rule deserves a name, so we extract it into a method called billable kg. Price multiplies the rate by billable kg, and no longer cares how that weight is worked out. But the new method reads four fields from the parcel, and it never uses the shipping service it hangs off.

Step 9: The rule moves onto Parcel Move Method

So it moves onto Parcel, where those four fields live. It reads them through its own receiver now, and price asks the parcel for its billable weight. Quote and price take four parameters each, where they took nine and seven when we started.

Payoff

Step 10: Fragile, in three edits Payoff

Now the fragile surcharge goes back in. Fragile is a fact about the parcel, so it becomes one more field on Parcel. Checkout passes the cart's flag where it builds the parcel, and price adds the surcharge, so that's three edits, each where the value is made or used. The quote signature, the price signature and the call inside quote didn't change.

Step 11: Why the clumps paid off Payoff

Each data clump is one type now, so a new fact about the parcel joins Parcel, and quote, which only passes values on, stays the same. And the two booleans no longer sit side by side, because express is a parameter and fragile lives inside the parcel. Passing the whole cart and customer would look shorter, but the origin is warehouse constants, and the shipping service would then depend on checkout's types. Two addresses can still be swapped, though, and the next lesson on domain types takes care of that.

Go bonus

Step 12: Name every field Go bonus

Checkout used to build the parcel from four floats by position, so two box sizes could trade places and the compiler would stay quiet. A Go struct literal can name each field, so every value now sits next to the field it fills. A width passed as a height now reads wrong on its own line, and go vet already asks for these names when the struct comes from another package. The addresses keep the short form, because each pair is two fields whose names already say which is which.

Recap

Step 13: Where we started, where we ended Before / after

On the left, quote took nine parameters and handed seven of them on to price. Four strings and four floats sat in runs of the same type, and any two in a run could trade places without the compiler noticing. On the right, two small structs hold the clumps, and the weight rule lives in the parcel. Price takes four parameters, the same four that quote takes now, and fragile is already in.

Step 14: When to reach for it Takeaways

Reach for a parameter object when the same group of values goes through several functions in the same order. Skip it for a function with a few unrelated values, like a log call with a level, a message and an error, because a wrapper would group things that don't belong together. You'll spot it by the same names repeated across signatures, long runs of floats or strings, and functions that only pass their parameters on. Go's time package already works this way, because one time value holds the whole date, so After compares two dates with a single argument.