Patterncore
Lazy Element
Also called lazy class.
A code smell: a class, a function or another program element does so little that it costs more to read and to keep than it gives, and the code is clearer without it.
- Family
- code-smell
- Intent
- Find the classes and functions that add a name and a layer but no meaning, and fold them into the code that uses them.
- Also called
- Lazy Class
- Refactorings
- Inline function, Inline class, Collapse hierarchy
Intent
Find the program elements that do too little to earn their place: a class with one trivial method, a function whose body says the same thing as its name, a subclass that adds nothing to its parent. Fold each one into the code that uses it, so that a reader has one less name to learn and one less layer to step through.
Problem
Structure has a cost. Each class and each function is a name to learn, a file or a block to open, and a step in a call chain that a reader must follow. That cost is worth paying when the element gives something back: a name that explains, a place that hides a decision, or a piece that is used in many places.
The second edition of Refactoring describes the smell as an element that is not needed: a function whose name reads the same as its body, or a class that is in effect one function.1 The first edition gave the smell the name Lazy Class, and spoke only of classes.2
The forces are these:
- An element can start lazy. It was made for growth that never came, which is close to Speculative Generality.
- An element can become lazy. Refactoring moves behaviour out of a class, and what is left is a shell. Refactoring gives both causes.1
- Small elements are not lazy in themselves. A one-line function with a good name, such as
isOverdue(invoice), says what a comparison of dates means. The smell is an element whose name adds nothing to its body. - A layer that only passes a call through makes the reader step through it to learn that it does nothing.
Solution
Refactoring names the refactorings by the kind of element.1 The catalogue at refactoring.com has a card for each, and gives Inline Method as another name for Inline Function.3
- A function: Inline Function. Replace each call with the body, then delete the function.
- A class: Inline Class. Move its fields and methods into the class that uses it, then delete it.
- A subclass or a superclass that adds nothing: Collapse Hierarchy. Merge it with its parent or its child.
Inline Function is the inverse of Extract Function. The test for which way to go is the name: if the name tells the reader more than the body, keep the function; if the body is as clear as the name, inline it.
Example
The code to show a person's name goes through a class with one method and a function that only calls that method. The two layers add no rule and no name that the body does not already say.
import assert from "node:assert/strict";
// Before: a class with one method, and a function that only forwards to it.
class NameFormatter {
format(person) {
return `${person.first} ${person.last}`;
}
}
const formatter = new NameFormatter();
function fullNameBefore(person) {
return formatter.format(person);
}
function greetingBefore(person) {
return `Hello, ${fullNameBefore(person)}`;
}
// After: one function, with the body inline.
function fullName(person) {
return `${person.first} ${person.last}`;
}
const greeting = (person) => `Hello, ${fullName(person)}`;
const ada = { first: "Ada", last: "Lovelace" };
assert.equal(greetingBefore(ada), "Hello, Ada Lovelace");
assert.equal(greeting(ada), greetingBefore(ada));
assert.equal(fullName(ada), fullNameBefore(ada));
console.log("greeting: tests pass");
greeting: tests pass
The second version keeps fullName, because the name says what the template means and three callers can share it. It removes the class, because a class with one stateless method and one instance is a function with extra steps. A reader who follows greeting now reaches the template in one step, not three.
| Language | What the example shows |
|---|---|
| JavaScript | a one-method class and a forwarding function, inlined, as above |
| Python | the same layers, inlined to one function |
| Java | a subclass that adds nothing, collapsed into its parent, and a forwarding method inlined |
| Go | an interface with one implementation and one method, replaced by a function |
# Before: a class with one method, and a function that only forwards to it.
class NameFormatter:
def format(self, person):
return f"{person['first']} {person['last']}"
formatter = NameFormatter()
def full_name_before(person):
return formatter.format(person)
def greeting_before(person):
return f"Hello, {full_name_before(person)}"
# After: one function, with the body inline.
def full_name(person):
return f"{person['first']} {person['last']}"
def greeting(person):
return f"Hello, {full_name(person)}"
ada = {"first": "Ada", "last": "Lovelace"}
assert greeting_before(ada) == "Hello, Ada Lovelace"
assert greeting(ada) == greeting_before(ada)
assert full_name(ada) == full_name_before(ada)
print("greeting: tests pass")
greeting: tests pass
- Python functions are values and can live at the top level of a module, so a class is not needed to group one function.
- If a caller elsewhere still imports
NameFormatter, inline the class at each import first, and delete it last.
public class Main {
// Before: a subclass that adds nothing, and a method that only forwards.
static class Person {
final String first;
final String last;
Person(String first, String last) {
this.first = first;
this.last = last;
}
String fullName() {
return first + " " + last;
}
}
static class NamedPerson extends Person {
NamedPerson(String first, String last) {
super(first, last);
}
String displayName() {
return fullName(); // forwards, and adds nothing
}
}
static String greetingBefore(NamedPerson p) {
return "Hello, " + p.displayName();
}
// After: the hierarchy is collapsed, and the caller uses fullName.
static String greeting(Person p) {
return "Hello, " + p.fullName();
}
public static void main(String[] args) {
NamedPerson before = new NamedPerson("Ada", "Lovelace");
Person after = new Person("Ada", "Lovelace");
if (!greetingBefore(before).equals("Hello, Ada Lovelace")) throw new AssertionError("before");
if (!greeting(after).equals(greetingBefore(before))) throw new AssertionError("after");
System.out.println("greeting: tests pass");
}
}
greeting: tests pass
NamedPersonhas no field and no rule of its own, so Collapse Hierarchy merges it intoPerson. Eachnew NamedPerson(...)becomesnew Person(...).displayNameis a second name forfullName. Inline Function replaces each call withfullName(), and the method goes away with the subclass.
package main
import "fmt"
type person struct{ first, last string }
// Before: an interface with one implementation, and one method that does little.
type nameFormatter interface {
Format(p person) string
}
type spaceFormatter struct{}
func (spaceFormatter) Format(p person) string { return p.first + " " + p.last }
func greetingBefore(f nameFormatter, p person) string {
return "Hello, " + f.Format(p)
}
// After: one function, and no interface to pass around.
func fullName(p person) string { return p.first + " " + p.last }
func greeting(p person) string { return "Hello, " + fullName(p) }
func main() {
ada := person{"Ada", "Lovelace"}
if greetingBefore(spaceFormatter{}, ada) != "Hello, Ada Lovelace" {
panic("before")
}
if greeting(ada) != greetingBefore(spaceFormatter{}, ada) {
panic("after")
}
fmt.Println("greeting: tests pass")
}
greeting: tests pass
- In Go, an interface with one implementation is a common form of this smell. Each caller must pass the implementation, and the reader must find it to learn what
Formatdoes. - If a test needs a fake formatter, the interface has a second user, and it is not lazy. Keep it then.
Consequences
The code has fewer names and fewer layers. A reader reaches the logic in fewer steps, and a search for a rule finds it in one place.
Inlining removes a seam. A class or an interface with one implementation can be the place where a test puts a fake, or where a second implementation is planned for the next release. If the second implementation is real and close, keep the seam. If it is only possible, the element is lazy now, and it can be extracted again when the need is real.
The smell is relative. A function that is lazy in a small program can be a useful name in a large one, where the same template is used in many places. The question is what the element gives to its readers now, not what it might give later.
How to fix it
- A function whose body is as clear as its name: Inline Function.1
- A class that does almost nothing: Inline Class.1
- A subclass or superclass that adds nothing: Collapse Hierarchy.1
- A layer that only forwards calls: see Middle Man and Remove Middle Man.
Variants and related patterns
Speculative Generality. An element made for a need that never came is often lazy as well. See Speculative Generality.
Middle Man. A class whose methods mostly forward to another class is a lazy element of a particular shape. See Middle Man.
Long Function. The opposite problem: too much in one element. Extract Function fixes it, and Inline Function undoes an extraction that went too far. See Long Function.
References
- Martin Fowler, with Kent Beck, Refactoring, Improving the Design of Existing Code, second edition, Addison-Wesley, 2018, Chapter 3, Bad Smells in Code, Lazy Element
- Martin Fowler, Refactoring, Improving the Design of Existing Code, Addison-Wesley, 1999, Chapter 3, Bad Smells in Code, Lazy Class
- Martin Fowler, Catalog of Refactorings, the cards Inline Function (alias Inline Method), Inline Class and Collapse Hierarchy
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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag DYFV9F Edit this page History Report an error Markdown