A Value Object is a handy way to combine multiple values in a single object. It sounds simple — you just make each value a property, right? Well, there’s usually more to it than that. There’s even an entire objc.io article about Value Objects. …So how do you define a new Value Object?
I believe in laziness. Let’s do as little work as possible!
[This post is part of the series TDD Sample App: The Complete Collection …So Far]
In the Marvel Browser iOS TDD sample app, the goal is to display comic characters whose names start with a given prefix. The Marvel Comics API offers many parameters for fetching characters. We want to use just three of them:
This will allow us to fetch the results a page at a time, and request the next page.
The page size will likely be a fixed quantity in the app. We could build a Service that knows this fixed quantity. It could also keep track of the offset, encapsulating “request the next page.”
I’ve written Services like that before. But the guidance given by Domain-Driven Design is “make the Service stateless.” Why?
Let’s picture what it means to make the Service stateless. In our example, it means the Service won’t track the prefix, the page size, or the page offset. We’ll track these values elsewhere in the app. The Service only does what it’s told. What we get is a Service that is ignorant about our app.
This makes testing easier. It also opens the door to reusability. As I wrote last time: when it comes to objects, ignorance is bliss!
So we’ll pass in three parameters. Let’s pass them together as a Value Object. Are you ready?
Instead of assembling another set of screenshots, I made a screencast — my shortest yet. It’s just three-and-a-half minutes long.
Whether you use Xcode or AppCode, be sure to get my free set of test snippets:
What do you think about stateless Service objects? Have I convinced any of you to try AppCode yet? Click here to leave a comment.TDD Sample App: The Complete Collection …So Far]
Jon is a coach and consultant on iOS Clean Code (Test Driven Development, unit testing, refactoring, design). He’s been practicing TDD since 2001. You can learn more about his background, or see what services he can bring to your organization.