Strongly Typed Primitives
No, I’m not talking about NEANDERTHALS (there’s a joke in there somewhere), but rather a technique that a colleague of mine, Josh Twist, has recently blogged about – “Avoiding Primitive Obsession to tip developers into the pit of success”. I’d always seen a pit as symbolic of failure, so I’m pretty pleased there’s such a thing as a pit of success – improves my odds massively J
I’ve drawn attention to this because it is an approach I discovered a few years back, and I love it. I just use a slightly different implementation to Josh;
public class Command
{
#region Structure
private string _name;
private Command(string name)
{
_name = name;
}
public string Name
{
get
{
return _name;
}
}
#endregion
#region Instances
public static Command Profile = new Command("Profile");
public static Command WebExecute = new Command("WebExecute");
#endregion
}
You can see that I use a single class to encapsulate both the behaviour of the Command class and the static instances of a Command.
I can’t really think of a convincing reason why one of these would be better over the other to be honest – I guess Josh’s approach means you could have different collections of commands (WebCommands, WindowsCommands, SomeOtherCommands), but I’ve never needed to do that. Any other reasons you can think of?
Still – read Josh’s post and see what you think. This kind of pattern is so simple yet so effective at eliminating mistypes, increasing code readability, and improving refactoring (just try deleting a command type and watch that compiler pick up everywhere you need to make a change!).
Good stuff.