July 19th, 2019
While working on the server project I realized that I’d be building a response depending on a request. Some of the responses would be similar or exactly the same — they would all incorporate the same types of data. I had a set collection of data organized by type (headers, status, body). Responses would have different combinations of these pieces. I likened this to a restaurant. You have a set menu of items, and you build meals based on individual orders that come through. For my server, as requests came in, I wanted to dynamically build responses tailored to each request, though the types of information each response would have would be the same. One of the crafters suggested that I use the builder pattern. I’ll be sharing what it is and how I implemented it as a way to build responses for my server.
Let me start by showing what my starting point was before I introduced the pattern.
I had a constructor that had pieces of what my my response would include. I’d have to create getters and setters, but eventually I’d be able to write something along the lines of:
But what if I wanted to add more items to the constructor or what if I wanted to standardize different items from the contructor with pre-set data for different responses. With this approach, I’m forced to always include each parameter and I can’t define data for paramenters in the event that I don’t want to send them. Also, I’d have to worry about the order of the parameters. This route what not going to fulfill my needs. Enter the builder pattern.
And to use it, I simply either directly build, in which case my attributes that are returned will be whatever initial values I have. Or I can set those values and return them when I build.
This approach is cleaner and more direct. You could even build with classes instead of primitive data types. I appreciate the builder pattern because it’s flexible and you can easily create complex objects with unique data or standard data all while avoiding constructor pollution.