<commit_before>---
layout: post
title: "From Primitive Obsession to Domain Modelling"
date: 2015-01-19 8:15 UTC
tags: [Software Design]
---
{% include JB/setup %}

<div id="post">
  <p>
    <em>A string is sometimes not a string. Model it accordingly.</em>
  </p>
  <p>
    Recently, I was reviewing some code that looked like this:
  </p>
  <p>
    <pre style="font-family:Consolas;font-size:13;color:black;"><span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">IHttpActionResult</span>&nbsp;Get(<span style="color:blue;">string</span>&nbsp;userName)
{
&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(<span style="color:blue;">string</span>.IsNullOrWhiteSpace(userName))
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">this</span>.BadRequest(<span style="color:#a31515;">&quot;Invalid&nbsp;user&nbsp;name.&quot;</span>);
 
&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;user&nbsp;=&nbsp;<span style="color:blue;">this</span>.repository.FindUser(userName.ToUpper());
&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">this</span>.Ok(user);
}</pre>
  </p>
  <p>
    There was a few things with this that struck me as a bit odd; most notably the use of IsNullOrWhiteSpace. When I review code, IsNullOrWhiteSpace is one of the many things I look for, because most people <a href="http://blog.ploeh.dk/2014/11/18/the-isnullorwhitespace-trap">use it incorrectly</a>.
  </p>
  <p>
    This made me ask the author of the code why he had chosen to use IsNullOrWhiteSpace, or, more specifically, what was wrong with a string with white space in it?
  </p>
  <p>
    The answer wasn't what I expected, though. The answer was that it was a <em>business rule</em> that the user name can't be all white space.
  </p>
  <p>
    You can't really argue about business logic.
  </p>
  <p>
    In this case, the rule even seems quite reasonable, but I was just <em>so</em> ready to have a discussion about invariants (pre- and postconditions) that I didn't see that one coming. It got me thinking, though.
  </p>
  <p>
    <strong>Where should business rules go?</strong>
  </p>
  <p>
    It seems like a reasonable business rule that a user name can't consist entirely of white space, but is it reasonable to put that business rule in a Controller? Does that mean that everywhere you have a user name string, you <em>must</em> remember to add the business rule to that code, in order to validate it? That sounds like the kind of duplication that actually hurts.
  </p>
  <p>
    Shouldn't business rules go in a proper Domain Model?
  </p>
  <p>
    This is where many programmers would start to write extension methods for strings, but that's just putting lipstick on a pig. What if you forget to call the appropriate extension method? What if a new developer on the team doesn't know about the appropriate extension method to use?
  </p>
  <p>
    The root problem here is <a href="http://blog.ploeh.dk/2011/05/25/DesignSmellPrimitiveObsession">Primitive Obsession</a>. Just because you <em>can</em> represent a value as a string, it doesn't mean that you always should.
  </p>
  <p>
    The <code>string</code> data type literally can represent <em>any</em> text. A <em>user name</em> (in the example domain above) can <em>not</em> be any text - we've already established that.
  </p>
  <p>
    <strong>Make it a type</strong>
  </p>
  <p>
    Instead of string, you can (and should) make <em>user name</em> a type. That type can encapsulate all the business rules in a single place, without violating DRY. This is what is meant by a <a href="http://martinfowler.com/eaaCatalog/domainModel.html">Domain Model</a>. In <a href="http://amzn.to/WBCwx7">Domain-Driven Design</a> terminology, a primitive like a string or a number can be turned into a Value Object. <a href="http://lostechies.com/jimmybogard"><NAME></a> already <a href="http://grabbagoft.blogspot.dk/2007/12/dealing-with-primitive-obsession.html">covered that ground years ago</a>, but here's how I would define a UserName class:
  </p>
  <p>
    <pre style="font-family:Consolas;font-size:13;color:black;"><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">class</span>&nbsp;<span style="color:#2b91af;">UserName</span>
{
&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">private</span>&nbsp;<span style="color:blue;">readonly</span>&nbsp;<span style="color:blue;">string</span>&nbsp;value;
 
&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;UserName(<span style="color:blue;">string</span>&nbsp;value)
&nbsp;&nbsp;&nbsp;&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(value&nbsp;==&nbsp;<span style="color:blue;">null</span>)
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">throw</span>&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">ArgumentNullException</span>(<span style="color:#a31515;">&quot;value&quot;</span>);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(!<span style="color:#2b91af;">UserName</span>.IsValid(value))
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">throw</span>&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">ArgumentException</span>(<span style="color:#a31515;">&quot;Invalid&nbsp;value.&quot;</span>,&nbsp;<span style="color:#a31515;">&quot;value&quot;</span>);
 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">this</span>.value&nbsp;=&nbsp;value;
&nbsp;&nbsp;&nbsp;&nbsp;}
 
&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:blue;">bool</span>&nbsp;IsValid(<span style="color:blue;">string</span>&nbsp;candidate)
&nbsp;&nbsp;&nbsp;&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(<span style="color:blue;">string</span>.IsNullOrEmpty(candidate))
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">false</span>;
 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;candidate.Trim().ToUpper()&nbsp;==&nbsp;candidate;
&nbsp;&nbsp;&nbsp;&nbsp;}
 
&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:blue;">bool</span>&nbsp;TryParse(<span style="color:blue;">string</span>&nbsp;candidate,&nbsp;<span style="color:blue;">out</span>&nbsp;<span style="color:#2b91af;">UserName</span>&nbsp;userName)
&nbsp;&nbsp;&nbsp;&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;userName&nbsp;=&nbsp;<span style="color:blue;">null</span>;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(<span style="color:blue;">string</span>.IsNullOrWhiteSpace(candidate))
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">false</span>;
 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;userName&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">UserName</span>(candidate.Trim().ToUpper());
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">true</span>;
&nbsp;&nbsp;&nbsp;&nbsp;}
 
&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:blue;">implicit</span>&nbsp;<span style="color:blue;">operator</span>&nbsp;<span style="color:blue;">string</span>(<span style="color:#2b91af;">UserName</span>&nbsp;userName)
&nbsp;&nbsp;&nbsp;&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;userName.value;
&nbsp;&nbsp;&nbsp;&nbsp;}
 
&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">override</span>&nbsp;<span style="color:blue;">string</span>&nbsp;ToString()
&nbsp;&nbsp;&nbsp;&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">this</span>.value.ToString();
&nbsp;&nbsp;&nbsp;&nbsp;}
 
&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">override</span>&nbsp;<span style="color:blue;">bool</span>&nbsp;Equals(<span style="color:blue;">object</span>&nbsp;obj)
&nbsp;&nbsp;&nbsp;&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;other&nbsp;=&nbsp;obj&nbsp;<span style="color:blue;">as</span>&nbsp;<span style="color:#2b91af;">UserName</span>;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(other&nbsp;==&nbsp;<span style="color:blue;">null</span>)
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">base</span>.Equals(obj);
 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">object</span>.Equals(<span style="color:blue;">this</span>.value,&nbsp;other.value);
&nbsp;&nbsp;&nbsp;&nbsp;}
 
&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">override</span>&nbsp;<span style="color:blue;">int</span>&nbsp;GetHashCode()
&nbsp;&nbsp;&nbsp;&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">this</span>.value.GetHashCode();
&nbsp;&nbsp;&nbsp;&nbsp;}
}</pre>
  </p>
  <p>
    As you can tell, this class protects its invariants. In case you were wondering about the use of ToUpper, it turns out that there's also another business rule that states that user names are case-insensitive, and one of the ways you can implement that is by converting the value to upper case letters. All business rules pertaining to user names are now nicely encapsulated in this single class, so you don't need to remember where to apply them to strings.
  </p>
  <p>
    If you want to know the underlying string, you can either invoke ToString, or take advantage of the implicit conversion from UserName to string. You can also compare to UserName instances, because the class overrides Equals. If you have a string, and want to convert it to a UserName, you can use TryParse.
  </p>
  <p>
    The original code example above can be refactored to use the UserName class instead:
  </p>
  <p>
    <pre style="font-family:Consolas;font-size:13;color:black;"><span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">IHttpActionResult</span>&nbsp;Get(<span style="color:blue;">string</span>&nbsp;candidate)
{
&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">UserName</span>&nbsp;userName;
&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(!<span style="color:#2b91af;">UserName</span>.TryParse(candidate,&nbsp;<span style="color:blue;">out</span>&nbsp;userName))
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">this</span>.BadRequest(<span style="color:#a31515;">&quot;Invalid&nbsp;user&nbsp;name.&quot;</span>);
 
&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;user&nbsp;=&nbsp;<span style="color:blue;">this</span>.repository.FindUser(userName);
&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">this</span>.Ok(user);
}</pre>
  </p>
  <p>
    This code has the same complexity as the original example, but now it's much clearer what's going on. You don't have to wonder about what looks like arbitrary rules; they're all nicely encapsulated in the UserName class.
  </p>
  <p>
    Furthermore, as soon as you've left the <a href="http://blog.ploeh.dk/2011/05/31/AttheBoundaries,ApplicationsareNotObject-Oriented">not Object-Oriented boundary of your system</a>, you can express the rest of your code in terms of the Domain Model; in this case, the UserName class. Here's the IUserRepository interface's Find method:
  </p>
  <p>
    <pre style="font-family:Consolas;font-size:13;color:black;"><span style="color:#2b91af;">User</span>&nbsp;FindUser(<span style="color:#2b91af;">UserName</span>&nbsp;userName);
</pre>
  </p>
  <p>
    As you can tell, it's expressed in terms of the Domain Model, so you can't accidentally pass it a string. From that point, since you're receiving a UserName instance, you <em>know</em> that it conforms to all business rules encapsulated in the UserName class.
  </p>
  <p>
    <strong>Not only for OOP</strong>
  </p>
  <p>
    While I've used the term <em>encapsulation</em> once or twice here, this way of thinking is in no way limited to Object-Oriented Programming. <a href="http://fsharpforfunandprofit.com">Scott Wlaschin</a> describes how to <a href="http://fsharpforfunandprofit.com/posts/designing-with-types-single-case-dus">wrap primitives in meaningful types in F#</a>. The motivation and the advantages you gain are the same in Functional F# as what I've described here.
  </p>
  <p>
    <strong>Over-engineering?</strong>
  </p>
  <p>
    Isn't this over-engineering? A 56 lines of code class instead of a string? Really? The answer to such a question is always context-dependent, but I rarely find that it is (over-engineering). You can create a Value Object like the above UserName class in less than half an hour - even if you use Test-Driven Development. When I created this example, I wrote 27 test cases distributed over five test methods in order to make sure that I hadn't done something stupid. It took me 15 minutes.
  </p>
  <p>
    You may argue that 15 minutes is a lot, compared to the 0 minutes it would take you if you'd 'just' use a string. On the surface, that seems like a valid counter-argument, but perhaps you're forgetting that with a primitive string, you still need to write validation and business logic 'around' the string, and you have to remember to apply that logic consistently across your entire code base. My guess is that you'll spend more than 15 minutes on doing this, and troubleshooting defects that occur when someone forgets to apply one of those rules to a string in some other part of the code base.
  </p>
  <p>
    <strong>Summary</strong>
  </p>
  <p>
    Primitive values such as strings, integers, decimal numbers, etc. often represent concepts that are constrained in some ways; they're not just <em>any</em> string, <em>any</em> integer, or <em>any</em> decimal number. Ask yourself if extreme values (like the entire <a href="http://amzn.to/19W4JHk">APPP</a> manuscript, <a href="http://msdn.microsoft.com/en-us/library/system.int32.minvalue.aspx">Int32.MinValue</a>, and so on) are suitable for such variables. If that's not the case, consider introducing a Value Object instead.
  </p>
  <p>
    If you want to learn more about Encapsulation, you can watch my <a href="http://www.shareasale.com/r.cfm?u=1017843&b=611266&m=53701&afftrack=&urllink=www%2Epluralsight%2Ecom%2Fcourses%2Fencapsulation%2Dsolid">Encapsulation and SOLID Pluralsight course</a>.
  </p>
</div><commit_msg>Comment - It's also good OO, imho<commit_after>---
layout: post
title: "From Primitive Obsession to Domain Modelling"
date: 2015-01-19 8:15 UTC
tags: [Software Design]
---
{% include JB/setup %}

<div id="post">
  <p>
    <em>A string is sometimes not a string. Model it accordingly.</em>
  </p>
  <p>
    Recently, I was reviewing some code that looked like this:
  </p>
  <p>
    <pre style="font-family:Consolas;font-size:13;color:black;"><span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">IHttpActionResult</span>&nbsp;Get(<span style="color:blue;">string</span>&nbsp;userName)
{
&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(<span style="color:blue;">string</span>.IsNullOrWhiteSpace(userName))
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">this</span>.BadRequest(<span style="color:#a31515;">&quot;Invalid&nbsp;user&nbsp;name.&quot;</span>);
 
&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;user&nbsp;=&nbsp;<span style="color:blue;">this</span>.repository.FindUser(userName.ToUpper());
&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">this</span>.Ok(user);
}</pre>
  </p>
  <p>
    There was a few things with this that struck me as a bit odd; most notably the use of IsNullOrWhiteSpace. When I review code, IsNullOrWhiteSpace is one of the many things I look for, because most people <a href="http://blog.ploeh.dk/2014/11/18/the-isnullorwhitespace-trap">use it incorrectly</a>.
  </p>
  <p>
    This made me ask the author of the code why he had chosen to use IsNullOrWhiteSpace, or, more specifically, what was wrong with a string with white space in it?
  </p>
  <p>
    The answer wasn't what I expected, though. The answer was that it was a <em>business rule</em> that the user name can't be all white space.
  </p>
  <p>
    You can't really argue about business logic.
  </p>
  <p>
    In this case, the rule even seems quite reasonable, but I was just <em>so</em> ready to have a discussion about invariants (pre- and postconditions) that I didn't see that one coming. It got me thinking, though.
  </p>
  <p>
    <strong>Where should business rules go?</strong>
  </p>
  <p>
    It seems like a reasonable business rule that a user name can't consist entirely of white space, but is it reasonable to put that business rule in a Controller? Does that mean that everywhere you have a user name string, you <em>must</em> remember to add the business rule to that code, in order to validate it? That sounds like the kind of duplication that actually hurts.
  </p>
  <p>
    Shouldn't business rules go in a proper Domain Model?
  </p>
  <p>
    This is where many programmers would start to write extension methods for strings, but that's just putting lipstick on a pig. What if you forget to call the appropriate extension method? What if a new developer on the team doesn't know about the appropriate extension method to use?
  </p>
  <p>
    The root problem here is <a href="http://blog.ploeh.dk/2011/05/25/DesignSmellPrimitiveObsession">Primitive Obsession</a>. Just because you <em>can</em> represent a value as a string, it doesn't mean that you always should.
  </p>
  <p>
    The <code>string</code> data type literally can represent <em>any</em> text. A <em>user name</em> (in the example domain above) can <em>not</em> be any text - we've already established that.
  </p>
  <p>
    <strong>Make it a type</strong>
  </p>
  <p>
    Instead of string, you can (and should) make <em>user name</em> a type. That type can encapsulate all the business rules in a single place, without violating DRY. This is what is meant by a <a href="http://martinfowler.com/eaaCatalog/domainModel.html">Domain Model</a>. In <a href="http://amzn.to/WBCwx7">Domain-Driven Design</a> terminology, a primitive like a string or a number can be turned into a Value Object. <a href="http://lostechies.com/jimmybogard"><NAME></a> already <a href="http://grabbagoft.blogspot.dk/2007/12/dealing-with-primitive-obsession.html">covered that ground years ago</a>, but here's how I would define a UserName class:
  </p>
  <p>
    <pre style="font-family:Consolas;font-size:13;color:black;"><span style="color:blue;">public</span>&nbsp;<span style="color:blue;">class</span>&nbsp;<span style="color:#2b91af;">UserName</span>
{
&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">private</span>&nbsp;<span style="color:blue;">readonly</span>&nbsp;<span style="color:blue;">string</span>&nbsp;value;
 
&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;UserName(<span style="color:blue;">string</span>&nbsp;value)
&nbsp;&nbsp;&nbsp;&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(value&nbsp;==&nbsp;<span style="color:blue;">null</span>)
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">throw</span>&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">ArgumentNullException</span>(<span style="color:#a31515;">&quot;value&quot;</span>);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(!<span style="color:#2b91af;">UserName</span>.IsValid(value))
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">throw</span>&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">ArgumentException</span>(<span style="color:#a31515;">&quot;Invalid&nbsp;value.&quot;</span>,&nbsp;<span style="color:#a31515;">&quot;value&quot;</span>);
 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">this</span>.value&nbsp;=&nbsp;value;
&nbsp;&nbsp;&nbsp;&nbsp;}
 
&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:blue;">bool</span>&nbsp;IsValid(<span style="color:blue;">string</span>&nbsp;candidate)
&nbsp;&nbsp;&nbsp;&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(<span style="color:blue;">string</span>.IsNullOrEmpty(candidate))
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">false</span>;
 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;candidate.Trim().ToUpper()&nbsp;==&nbsp;candidate;
&nbsp;&nbsp;&nbsp;&nbsp;}
 
&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:blue;">bool</span>&nbsp;TryParse(<span style="color:blue;">string</span>&nbsp;candidate,&nbsp;<span style="color:blue;">out</span>&nbsp;<span style="color:#2b91af;">UserName</span>&nbsp;userName)
&nbsp;&nbsp;&nbsp;&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;userName&nbsp;=&nbsp;<span style="color:blue;">null</span>;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(<span style="color:blue;">string</span>.IsNullOrWhiteSpace(candidate))
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">false</span>;
 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;userName&nbsp;=&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">UserName</span>(candidate.Trim().ToUpper());
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">true</span>;
&nbsp;&nbsp;&nbsp;&nbsp;}
 
&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:blue;">implicit</span>&nbsp;<span style="color:blue;">operator</span>&nbsp;<span style="color:blue;">string</span>(<span style="color:#2b91af;">UserName</span>&nbsp;userName)
&nbsp;&nbsp;&nbsp;&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;userName.value;
&nbsp;&nbsp;&nbsp;&nbsp;}
 
&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">override</span>&nbsp;<span style="color:blue;">string</span>&nbsp;ToString()
&nbsp;&nbsp;&nbsp;&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">this</span>.value.ToString();
&nbsp;&nbsp;&nbsp;&nbsp;}
 
&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">override</span>&nbsp;<span style="color:blue;">bool</span>&nbsp;Equals(<span style="color:blue;">object</span>&nbsp;obj)
&nbsp;&nbsp;&nbsp;&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;other&nbsp;=&nbsp;obj&nbsp;<span style="color:blue;">as</span>&nbsp;<span style="color:#2b91af;">UserName</span>;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(other&nbsp;==&nbsp;<span style="color:blue;">null</span>)
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">base</span>.Equals(obj);
 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">object</span>.Equals(<span style="color:blue;">this</span>.value,&nbsp;other.value);
&nbsp;&nbsp;&nbsp;&nbsp;}
 
&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">override</span>&nbsp;<span style="color:blue;">int</span>&nbsp;GetHashCode()
&nbsp;&nbsp;&nbsp;&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">this</span>.value.GetHashCode();
&nbsp;&nbsp;&nbsp;&nbsp;}
}</pre>
  </p>
  <p>
    As you can tell, this class protects its invariants. In case you were wondering about the use of ToUpper, it turns out that there's also another business rule that states that user names are case-insensitive, and one of the ways you can implement that is by converting the value to upper case letters. All business rules pertaining to user names are now nicely encapsulated in this single class, so you don't need to remember where to apply them to strings.
  </p>
  <p>
    If you want to know the underlying string, you can either invoke ToString, or take advantage of the implicit conversion from UserName to string. You can also compare to UserName instances, because the class overrides Equals. If you have a string, and want to convert it to a UserName, you can use TryParse.
  </p>
  <p>
    The original code example above can be refactored to use the UserName class instead:
  </p>
  <p>
    <pre style="font-family:Consolas;font-size:13;color:black;"><span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">IHttpActionResult</span>&nbsp;Get(<span style="color:blue;">string</span>&nbsp;candidate)
{
&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">UserName</span>&nbsp;userName;
&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;(!<span style="color:#2b91af;">UserName</span>.TryParse(candidate,&nbsp;<span style="color:blue;">out</span>&nbsp;userName))
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">this</span>.BadRequest(<span style="color:#a31515;">&quot;Invalid&nbsp;user&nbsp;name.&quot;</span>);
 
&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">var</span>&nbsp;user&nbsp;=&nbsp;<span style="color:blue;">this</span>.repository.FindUser(userName);
&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:blue;">this</span>.Ok(user);
}</pre>
  </p>
  <p>
    This code has the same complexity as the original example, but now it's much clearer what's going on. You don't have to wonder about what looks like arbitrary rules; they're all nicely encapsulated in the UserName class.
  </p>
  <p>
    Furthermore, as soon as you've left the <a href="http://blog.ploeh.dk/2011/05/31/AttheBoundaries,ApplicationsareNotObject-Oriented">not Object-Oriented boundary of your system</a>, you can express the rest of your code in terms of the Domain Model; in this case, the UserName class. Here's the IUserRepository interface's Find method:
  </p>
  <p>
    <pre style="font-family:Consolas;font-size:13;color:black;"><span style="color:#2b91af;">User</span>&nbsp;FindUser(<span style="color:#2b91af;">UserName</span>&nbsp;userName);
</pre>
  </p>
  <p>
    As you can tell, it's expressed in terms of the Domain Model, so you can't accidentally pass it a string. From that point, since you're receiving a UserName instance, you <em>know</em> that it conforms to all business rules encapsulated in the UserName class.
  </p>
  <p>
    <strong>Not only for OOP</strong>
  </p>
  <p>
    While I've used the term <em>encapsulation</em> once or twice here, this way of thinking is in no way limited to Object-Oriented Programming. <a href="http://fsharpforfunandprofit.com"><NAME>in</a> describes how to <a href="http://fsharpforfunandprofit.com/posts/designing-with-types-single-case-dus">wrap primitives in meaningful types in F#</a>. The motivation and the advantages you gain are the same in Functional F# as what I've described here.
  </p>
  <p>
    <strong>Over-engineering?</strong>
  </p>
  <p>
    Isn't this over-engineering? A 56 lines of code class instead of a string? Really? The answer to such a question is always context-dependent, but I rarely find that it is (over-engineering). You can create a Value Object like the above UserName class in less than half an hour - even if you use Test-Driven Development. When I created this example, I wrote 27 test cases distributed over five test methods in order to make sure that I hadn't done something stupid. It took me 15 minutes.
  </p>
  <p>
    You may argue that 15 minutes is a lot, compared to the 0 minutes it would take you if you'd 'just' use a string. On the surface, that seems like a valid counter-argument, but perhaps you're forgetting that with a primitive string, you still need to write validation and business logic 'around' the string, and you have to remember to apply that logic consistently across your entire code base. My guess is that you'll spend more than 15 minutes on doing this, and troubleshooting defects that occur when someone forgets to apply one of those rules to a string in some other part of the code base.
  </p>
  <p>
    <strong>Summary</strong>
  </p>
  <p>
    Primitive values such as strings, integers, decimal numbers, etc. often represent concepts that are constrained in some ways; they're not just <em>any</em> string, <em>any</em> integer, or <em>any</em> decimal number. Ask yourself if extreme values (like the entire <a href="http://amzn.to/19W4JHk">APPP</a> manuscript, <a href="http://msdn.microsoft.com/en-us/library/system.int32.minvalue.aspx">Int32.MinValue</a>, and so on) are suitable for such variables. If that's not the case, consider introducing a Value Object instead.
  </p>
  <p>
    If you want to learn more about Encapsulation, you can watch my <a href="http://www.shareasale.com/r.cfm?u=1017843&b=611266&m=53701&afftrack=&urllink=www%2Epluralsight%2Ecom%2Fcourses%2Fencapsulation%2Dsolid">Encapsulation and SOLID Pluralsight course</a>.
  </p>
</div>


<div id="comments">
    <hr>
    <h2 id="comments-header">
        Comments
    </h2>
    <div class="comment">
        <div class="comment-author">Johannes</div>
        <div class="comment-content">
            <p>
Mark, I enjoyed your article. I feel that this is the way to go. Too often have I seen people using 
arrays if bytes for images and strings for email addresses.
</p>
<p>
An important aspect of DDD is within the language and when there are people talking
about user names all the time, that usually indicates that usernames are 
an important aspect of what is going on and should be modeled explicitly and not use primitives.
</p>
<p>
The solution doesn't look overengineered to me, although I had to defend similar code
before for the same reason. Not only is it now a good place to put further validation, but also allows further distinction
using other types and a polymorphism (if carefully used, they can be a delight), each 
of which covers different invariants. 
</p>
<p>
A UserName can be moved around and used to retrieve objects. But maybe you
can't do that with a class of the type InvalidUsername. In another example, maybe 
there are functions that deal with email eddresses 
- which I have often seen modeled as strings. Some accept InvalidEmailAddress objects, 
others accept ValidEmail addresses. While it doesn't reduce the amount of boilerplate null checks,
a SendEmail function wouldn't have to do 
</p>
<pre><code>
... SendEmail(EmailAddress email)
{
    if(email.IsValid()) {
        email.Send()
    }
}
</code></pre>
<p>
One could simply make it to only accept valid email addresses. Their mere existence
would guarantee, that the email address is valid. One could then write functions dealing with 
valid email addresses and some dealing with invalid ones. You can log and analyze bad
account creation requests with the invalid ones, but not send email to them and prevent
everyone else from doing so, depending on what kind of email address is being passed around. 
</p>

        </div>
        <div class="comment-date">2015-01-20 08:16 UTC</div>
    </div>
</div>
{'fraction_non_alphanumeric': 0.17683500865498497, 'fraction_numerical': 0.010021561541498376, 'mean_word_length': 6.591055786076533, 'pattern_counts': {'":': 0, '<': 733, '<?xml version=': 0, '>': 733, 'https://': 0, 'lorem ipsum': 0, 'www.': 4, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '829256', 'n_tokens_mistral': 10900, 'n_tokens_neox': 10059, 'n_words': 2856}