I’m writing a wrapper for a REST API (which is a static class with static methods) at work and it should return a class or a struct holding all the parsed Json returned from the API request. I’m parsing the Json using System.Web.Script.Serialization like so:
JavaScriptSerializer jss = new JavaScriptSerializer();
QueryResult re = jss.Deserialize<QueryResult>(json);
I then want to set two additional parameters on the QueryResult: the original Request Url used and the exact Json returned by the API. The one contradiction is that I want the entire object to be read only once it’s returned from the API wrapper. My first thought is to only let the variables be set through a constructor, but parsing Json the way that I am never lets me use a constructor. I thought about having two objects that are very similar, i.e. a private class that can’t be seen outside of the wrapper that is used for parsing and then a public class who uses a constructor to set the read only parameters once, but that’s very redundant and I’d rather do it just about any other way.
Are their any design patterns or tips to let me do this? I want it to be a syntactical error for them to try and assign to one of the properties, not just an ignored assignment.
Update:
This sounds like an appropriate use case for the builder pattern. You have a mutable object that you can use just to set up the state of whatever you want to build; then this type is responsible for constructing an instance of an immutable (“locked down”) type which is actually usable.
For example:
Then your calling code might look like this:
I honestly have no idea if this is an appropriate answer for your scenario, but one common solution to the “read-only object that can be ‘updated'” problem is to have an immutable type that returns copies with modifications (much like
DateTime.Add, for example).So you could have an operation like…
Then calling code would need to do something like: