Feature Envy: I Wanna Hold Your Hand
Feature Envy Example
In the
Customer
class below, the method getMobilePhoneNumber()
provides a North American-formatted mobile Phone
number:
public class Phone {
private final String unformattedNumber; public Phone(String unformattedNumber) {
this.unformattedNumber = unformattedNumber;
} public String getAreaCode() {
return unformattedNumber.substring(0,3);
} public String getPrefix() {
return unformattedNumber.substring(3,6);
} public String getNumber() {
return unformattedNumber.substring(6,10);
}
}public class Customer {
private Phone mobilePhone; public String getMobilePhoneNumber() {
return "(" +
mobilePhone.getAreaCode() + ") " +
mobilePhone.getPrefix() + "-" +
mobilePhone.getNumber();
}
}
See how
Customer
reaches into Phone
’s data to format the number?
Feature Envy often shows up as a misplaced responsibility.
public class Phone {
private final String unformattedNumber; public Phone(String unformattedNumber) {
this.unformattedNumber = unformattedNumber;
} private String getAreaCode() {
return unformattedNumber.substring(0,3);
} private String getPrefix() {
return unformattedNumber.substring(3,6);
} private String getNumber() {
return unformattedNumber.substring(6,10);
} public String toFormattedString() {
return "(%s) %s-%s".formatted(getAreaCode(), getPrefix(), getNumber());
}
}public class Customer {
private Phone mobilePhone; public String getMobilePhoneNumber() {
return mobilePhone.toFormattedString();
}
}
Now
Customer
relies on Phone
to do the formatting.
(Reading...)
Formatting Hints:
To format... | use this markup: |
---|---|
source code | {source:lang=java|lineNumbers=false}...{source} (Supported languages: java, cpp, csharp, c, python.) |
bold text | __some text__ |
italicized text | ~~some text~~ |
underlined text | @@some text@@ |
a method or class name | ``myMethod(...)`` |