How to convert a Ruby primitive to a custom domain object in two minutes
You already know why you want to use domain objects instead of Ruby’s built-in primitives… but what do you do if you’ve already used strings and integers all over the place? Did you code yourself into a corner? Are you going to have to change lots of code, and potentially break things? Of course not! You can convert a Ruby primitive into a custom domain object in just a few minutes… here’s how you do it:
- Wrap the primitive with a new custom object, and define
- Replace equality comparisons with domain methods
Example: Convert a Ruby primitive into a custom domain object
We’ll start with a simple class that fetches an HTTP page:
It just fetches the response using
Net::HTTP and returns the status code. Now, let’s refactor the
String primitive to a custom domain object!
Step 1: Wrap the primitive with a new custom object, and define
Simply add a new class, and use it to wrap the return value. You won’t even have to change any tests! Check it out…
Step 2. Replace equality comparisons with domain methods
Now that you’re returning a custom object, you can introduce domain methods. You just encapsulate the original comparison in a method. Easy!
Let your new object attract behavior
Now that you have a new domain object, you’ve got a great place to put related behavior! Try it and see what happens…