Showing posts with label refactoring. Show all posts
Showing posts with label refactoring. Show all posts

Friday, August 18, 2017

Refactor a lot, but only when it's appropriate

Don't just refactor for fun. Refactor in service of delivering business value. If there's some terrible code that you never need to touch, then there's no reason to change it. Leave it terrible.

So, when are the right times to refactor?

  • When you're changing code. Refactor to make it well-designed for its new purpose.
  • When you're reading code. Every time you gain some understanding, refactor to record that understanding. Lots of renames.
  • When you're afraid of code. If there's code you should be changing or reading, but you avoid because it's such a mess, then you should definitely refactor it.
Note that this refactoring is a small improvement each time, not a dramatic major rewrite. The goal is Better, not Good.


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