Smell Detail

Data Class

纯数据类

Dispensables

The class only contains fields and accessor methods and has no other functionality.

Define

Introduction

A Data Class contains only data and simple accessor methods, with no behavior. Such classes often indicate that behavior has been placed in the wrong location.

Key Identifiers

  • The class contains only fields and getter/setter methods
  • No business logic or behavioral methods
  • Related behavior is scattered across other classes
  • Violates the object-oriented principle of encapsulation

Refactoring Suggestions

  1. Move Method: Move related behavior into the data class
  2. Encapsulate Field: Reduce unnecessary setter methods
  3. Add Behavior: Add meaningful domain methods to the data class

Explanation

The Customer class is merely a data container; related business behavior should be moved into the Customer class so that data and behavior stay together.

Code Example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Customer {
private String name;
private String email;
private String address;
private double creditLimit;
// Only getters and setters, no other behavior
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getEmail() { return email; }
public void setEmail(String email) { this.email = email; }
public String getAddress() { return address; }
public void setAddress(String address) { this.address = address; }
public double getCreditLimit() { return creditLimit; }
public void setCreditLimit(double creditLimit) { this.creditLimit = creditLimit; }
}
// Behavior is placed in other classes
class CustomerService {
public boolean canPurchase(Customer customer, double amount) {
return customer.getCreditLimit() >= amount;
}
public void updateCreditLimit(Customer customer, double newLimit) {
customer.setCreditLimit(newLimit);
}
}