Programming Search⌘K

Patterncore

Feature Envy

A code smell: a function uses the data and the functions of another module more than those of its own, so the rule it computes lives far from the data it depends on.

Family
code-smell
Intent
Find the functions that work mostly on the data of another module, and move them, or the envious part of them, to that module.

Intent

Find the functions that are more interested in another module than in their own, and move them to the module whose data they use. Then the rule and the data that it reads change together, in one place.

Problem

A design splits a program into modules so that the code inside a module works together closely, and the modules talk to each other as little as possible. Refactoring describes Feature Envy as a function in one module that spends more of its time with the functions or the data of another module than with its own.1 A common form is a function that calls several getters of one object to compute a value from them.1

The forces are these:

  • The function was written where it was first needed. The code that withdraws cash needed to know if an account allows the withdrawal, so the check was written in the cash module, from the fields of the account.
  • A rule that lives outside its data must be found when the data changes. If the account gets one more field, such as a daily limit, the programmer must know to look in the cash module.
  • Other modules need the same rule. Each one either calls into the cash module, which is a strange dependency, or writes its own copy.
  • Getters make the smell cheap to write. Each field that an object exposes is one more thing that code in other modules can reach for.

Fowler's article on Tell Don't Ask describes the same pull. It says that "object-orientation is about bundling data with the functions that operate on that data", and that "rather than asking an object for data and acting on that data, we should instead tell an object what to do."2

Solution

Refactoring gives the fix in three cases.1 The catalogue at refactoring.com has the cards for the two refactorings, and gives Move Method as another name for Move Function.3 Move Method is the name that the first edition uses.4

  1. The whole function envies one module: Move Function to that module.
  2. Only part of the function envies another module: Extract Function on that part, then Move Function on the result.
  3. The function uses data from several modules: move it to the module that has most of the data it uses, or extract the parts and move each one to its own module.

Refactoring also gives the principle behind the rule: put together the things that change together.1 Data and the behaviour that reads it usually change together.

Example

The function canWithdrawBefore lives in the cash machine module. It reads three fields of the account and none of its own module. After the move, it is a method of the account.

import assert from "node:assert/strict";

class Account {
  constructor(balance, overdraftLimit, frozen = false) {
    this.balance = balance;
    this.overdraftLimit = overdraftLimit;
    this.frozen = frozen;
  }

  // After: the rule lives with the data it reads.
  canWithdraw(amount) {
    return !this.frozen && this.balance + this.overdraftLimit >= amount;
  }
}

// Before: the cash machine module asks the account for its data.
function canWithdrawBefore(account, amount) {
  if (account.frozen) return false;
  return account.balance + account.overdraftLimit >= amount;
}

const cases = [
  [new Account(100, 50), 150, true],
  [new Account(100, 50), 151, false],
  [new Account(100, 0, true), 10, false],
];
for (const [account, amount, expected] of cases) {
  assert.equal(canWithdrawBefore(account, amount), expected);
  assert.equal(account.canWithdraw(amount), expected);
}
console.log("canWithdraw: tests pass");
Output
canWithdraw: tests pass

The test runs the same cases on both versions. After the move, a change to the rule, such as a daily limit, is a change to Account and its tests. The cash machine calls account.canWithdraw(amount) and no longer needs to know which fields the rule reads.

Language What the example shows
JavaScript a function moved into a class as a method
Python the same move, into a dataclass
Java a method that called three getters, moved into the class; the getters can then become private
Go a function moved to a method on the struct
PythonGitHub
from dataclasses import dataclass


@dataclass
class Account:
    balance: int
    overdraft_limit: int
    frozen: bool = False

    # After: the rule lives with the data it reads.
    def can_withdraw(self, amount):
        return not self.frozen and self.balance + self.overdraft_limit >= amount


# Before: the cash machine module asks the account for its data.
def can_withdraw_before(account, amount):
    if account.frozen:
        return False
    return account.balance + account.overdraft_limit >= amount


cases = [
    (Account(100, 50), 150, True),
    (Account(100, 50), 151, False),
    (Account(100, 0, frozen=True), 10, False),
]
for account, amount, expected in cases:
    assert can_withdraw_before(account, amount) == expected
    assert account.can_withdraw(amount) == expected
print("can_withdraw: tests pass")
Output
can_withdraw: tests pass
  • The @dataclass decorator writes the constructor from the field list. The method sits in the class body next to the fields that it reads.
  • Python has no private fields. A leading underscore, such as _overdraft_limit, tells other modules that the field is not part of the interface, once the rule no longer needs to be outside the class.
JavaGitHub
public class Main {
    static final class Account {
        private final long balance;
        private final long overdraftLimit;
        private final boolean frozen;

        Account(long balance, long overdraftLimit, boolean frozen) {
            this.balance = balance;
            this.overdraftLimit = overdraftLimit;
            this.frozen = frozen;
        }

        // Before the move, other classes needed these three getters.
        long getBalance() { return balance; }
        long getOverdraftLimit() { return overdraftLimit; }
        boolean isFrozen() { return frozen; }

        // After: the rule lives with the data it reads.
        boolean canWithdraw(long amount) {
            return !frozen && balance + overdraftLimit >= amount;
        }
    }

    // Before: the cash machine class asks the account for its data.
    static boolean canWithdrawBefore(Account account, long amount) {
        if (account.isFrozen()) return false;
        return account.getBalance() + account.getOverdraftLimit() >= amount;
    }

    static void check(boolean ok, String what) {
        if (!ok) throw new AssertionError(what);
    }

    public static void main(String[] args) {
        Object[][] cases = {
            {new Account(100, 50, false), 150L, true},
            {new Account(100, 50, false), 151L, false},
            {new Account(100, 0, true), 10L, false},
        };
        for (Object[] c : cases) {
            Account account = (Account) c[0];
            long amount = (Long) c[1];
            boolean expected = (Boolean) c[2];
            check(canWithdrawBefore(account, amount) == expected, "before " + amount);
            check(account.canWithdraw(amount) == expected, "after " + amount);
        }
        System.out.println("canWithdraw: tests pass");
    }
}
Output
canWithdraw: tests pass
  • canWithdrawBefore makes three getter calls on one object and no call on its own class. That count is the sign of the smell.
  • After the move, canWithdraw reads the private fields directly. If no other class calls the getters, they can be removed, and the fields are then hidden behind the one method.
package main

import "fmt"

type Account struct {
	Balance        int
	OverdraftLimit int
	Frozen         bool
}

// After: the rule is a method on the type whose data it reads.
func (a Account) CanWithdraw(amount int) bool {
	return !a.Frozen && a.Balance+a.OverdraftLimit >= amount
}

// Before: the cash machine package reads the fields of the account.
func canWithdrawBefore(a Account, amount int) bool {
	if a.Frozen {
		return false
	}
	return a.Balance+a.OverdraftLimit >= amount
}

func main() {
	cases := []struct {
		account  Account
		amount   int
		expected bool
	}{
		{Account{100, 50, false}, 150, true},
		{Account{100, 50, false}, 151, false},
		{Account{100, 0, true}, 10, false},
	}
	for _, c := range cases {
		if canWithdrawBefore(c.account, c.amount) != c.expected {
			panic(fmt.Sprintf("before %d", c.amount))
		}
		if c.account.CanWithdraw(c.amount) != c.expected {
			panic(fmt.Sprintf("after %d", c.amount))
		}
	}
	fmt.Println("CanWithdraw: tests pass")
}
Output
CanWithdraw: tests pass
  • In Go, a method must be declared in the same package as its type. Moving the function to a method also moves it to the package of Account.
  • The fields start with a capital letter, so other packages can read them. After the move, they can be renamed to balance and overdraftLimit, which hides them outside the package.

Consequences

The rule and its data are in one place. The fields that only the rule used can become private, so the module exposes less. Other callers get the rule without a dependency on the module where it used to live.

A move can go too far. Fowler warns, in the same article, of people who become "GetterEradicators", and says that "there are times when objects collaborate effectively by providing information."2 A report that reads the fields of ten kinds of objects is not ten cases of Feature Envy. It is a report, and its job is to read.

Some designs separate behaviour from data on purpose. Refactoring names the Strategy and Visitor patterns of the Gang of Four book as exceptions: they put behaviour in a separate object, so that the behaviour can vary without a change to the data.1 Fowler adds that co-locating data and behaviour "should sometimes be dropped in favor of other concerns - such as layering."2 In those designs the envy is the cost of a choice, not a mistake.

How to fix it

  • The whole function reads another module: Move Function.1
  • One part of the function reads another module: Extract Function, then Move Function.1
  • The function reads several modules: move it to the one with the most data it uses, or split it first.1
  • A chain of getters to reach the data: see Message Chains and Hide Delegate.

Data Class. A class with fields and getters and no behaviour is often the other side of Feature Envy: its behaviour lives in the classes that envy it. See Data Class.

Insider Trading. Two modules that exchange too much data with each other. See Insider Trading.

Strategy and Visitor. Patterns that keep behaviour apart from data on purpose. See Strategy pattern and Visitor pattern.

Law of Demeter. A rule that a method should talk only to its close collaborators, which limits the reach that envy needs. See Law of Demeter.

References

  1. Martin Fowler, with Kent Beck, Refactoring, Improving the Design of Existing Code, second edition, Addison-Wesley, 2018, Chapter 3, Bad Smells in Code, Feature Envy
  2. Martin Fowler, Tell Don't Ask, bliki, the definition, the monitor example and note 1
  3. Martin Fowler, Catalog of Refactorings, the cards Move Function (alias Move Method) and Extract Function
  4. Martin Fowler, Refactoring, Improving the Design of Existing Code, Addison-Wesley, 1999, Chapter 3, Bad Smells in Code, Feature Envy

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/4X6W70/text.yaml