Code
Code Smell: Primitive Obsession
We coders can't even keep track of a few primitives. Can we just accept that and adjust our style or do we want to continue obsessing over primitive obsession?
Technical Essays Referenced UML example of taking what might be primitive types (Contact and SocialSecurity as string, in this case) and removing the primitive and substituting it with a user-defined type public class Customer
{
public string Name { get ; private set ; }
public string Email { get ; private set ; }
public Customer ( string name, string email)
{
if ( string . IsNullOrWhiteSpace ( name) || name. Length > 50 )
throw new ArgumentException ( "Name is invalid" ) ;
if ( string . IsNullOrWhiteSpace ( email) || email. Length > 100 )
throw new ArgumentException ( "E-mail is invalid" ) ;
if ( ! Regex. IsMatch ( email, @"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$" ) )
throw new ArgumentException ( "E-mail is invalid" ) ;
Name = name;
Email = email;
}
public void ChangeName ( string name)
{
if ( string . IsNullOrWhiteSpace ( name) || name. Length > 50 )
throw new ArgumentException ( "Name is invalid" ) ;
Name = name;
}
public void ChangeEmail ( string email)
{
if ( string . IsNullOrWhiteSpace ( email) || email. Length > 100 )
throw new ArgumentException ( "E-mail is invalid" ) ;
if ( ! Regex. IsMatch ( email, @"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$" ) )
throw new ArgumentException ( "E-mail is invalid" ) ;
Email = email;
}
}
The author says that you can't keep using primitives! Your validation code will end up being duplicated and scattered all over the architecture! Well? Yes and no. It depends on what kind of architecture you're building. DRY can be a very bad thing in one scenario and absolutely necessary in another. Don't use a LOTR architecture strategy if you don't need to (Also of note, from Lobsters reader @corbin, "How Futile are Mindless Assessments of Roundoff in Floating-Point Computation? ")
A nice primitive obsession propaganda meme from the web
Comments (0)