Working from a C#
and EntityFramework
background. Jimmy Bogard makes the point of modelling your domain model correctly, such that an Email Address is not a simple string
but should be of type EmailAddress
.
Also known as Primitive Obsession.
I've come to this part of a piece of software where a Application form is to be filled out.
For the user a Yes/No question where they can answer Yes or No is a very easy thing, you can even create really go user experiences around yes/no.
So I have quickly thought of two ways to handle Yes/No.
A complex object:
public class YesNoAnswer
{
public YesNoAnswer(string state)
{
this.SetState(state);
}
public bool Yes { get; private set; }
public void SetState(string state)
{
var uppedState = state.ToUpper();
if (uppedState == "YES")
{
this.Yes = true;
return;
}
if (uppedState == "NO")
{
this.Yes = false;
return;
}
throw new ArgumentOutOfRangeException(nameof(state), "Yes or No strings not found in argument");
}
}
Or a simple extension method:
public static class StringExtensions
{
public static bool GetYesNoState(this string state)
{
var uppedState = state.ToUpper();
if (uppedState == "YES")
{
return true;
}
if (uppedState == "NO")
{
return false;
}
throw new ArgumentOutOfRangeException(nameof(state), "Yes or No strings not found in argument");
}
}
Obviously the validation should be done earlier in the pipeline (or at least it is in our application).
Which is better? They both achieve the same thing, the first is much clearer, neater. The second is well, slightly obfuscated - not a great deal but takes more than a second to think about what it is doing.
Usage of both
var application = new ApplicationForm { IsOkayToWork = new YesNoAnswer(state) };
or
var application = new ApplicationForm { IsOkayToWork = state.GetYesNoState() };
YesNoAnswer
has no property/field calledNo
andstring
doesn't have eitherYes
orNo
. \$\endgroup\$IsOkayToWork
everytime you want assign a new value? \$\endgroup\$NO
shouldreturn false
2) I don't think you're allowed to edit code like that. \$\endgroup\$