Wednesday, August 2, 2017

You really should get rid of those strings.

If you're looking for something to improve in your code, the #1 thing is not in this blog post. It's Naming is a Process.

The #2 might be eliminating the Primitive Obsession of string parameters to functions. The short recipe is:

1. Pick a string parameter to some method.
2. Write a new trivial value type* that contains that string.
3. Fix the method.
4. Fix all callers.
5. Let the type propogate.

You can often figure out the name of the new type from the name of the parameter:

string attributeName;   // <-- suggests an `AttributeName` type

string previousZipCode; // <-- suggests a `ZipCode` type

Why?

- It gives you a place to hang behaviors, eventually growing into a Whole Value.

- Eliminates bugs where you pass a CustomerId where only an OrderId is allowed (assuming strong types)

This isn't a strict rule. Don't go out and do this to every string parameter you have right now. Do it a bit at a time, in code you already need to change or understand, when you're pretty sure what the new class should be.

*Value Type in the DDD sense and not in the C# sense

No comments: