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 readonly string unformattedNumber; public Phone(String unformattedNumber)
{
this.unformattedNumber = unformattedNumber;
} internal string AreaCode
{
get
{
return unformattedNumber.Substring(0,3);
}
} internal string Prefix
{
get
{
return unformattedNumber.Substring(3,3);
}
} internal string Number
{
get
{
return unformattedNumber.Substring(6,4);
}
}
}public class Customer…
private readonly Phone mobilePhone; public string MobilePhoneNumber
{
get
{
return "(" + mobilePhone.AreaCode + ") " + mobilePhone.Prefix + "-" + mobilePhone.Number;
}
}
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 readonly string unformattedNumber; public Phone(String unformattedNumber)
{
this.unformattedNumber = unformattedNumber;
} internal string AreaCode
{
get
{
return unformattedNumber.Substring(0,3);
}
} internal string Prefix
{
get
{
return unformattedNumber.Substring(3,3);
}
} internal string Number
{
get
{
return unformattedNumber.Substring(6,4);
}
} public String ToFormattedString()
{
return "(" + AreaCode + ") " + Prefix + "-" + Number;
}
}public class Customer…
private readonly Phone mobilePhone; public string MobilePhoneNumber
{
get
{
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(...)`` |