Reputation: 204
I have a class that represents data returned from a RESTful API. The data returned may contain a lot of different fields or arrays that I want to represent with my object. There may be something like 20 different fields I may have to initialize when the object is created. Some of those fields may be empty depending on the ID I'm trying to get back. I need to do some basic validation to make sure I'm only initializing the fields for values that exist. A simple null/empty check should suffice for this but I don't want a lot of repeated code.
Is there any way to easily accomplish this with magic methods or do I need to manually validate everything with a helper method of some sort?
Upvotes: 0
Views: 38
Reputation: 19
a couple mouth ago I was worked on a Rest JSON API Wrapper.
Array with loop
My first Idea was to put all my field in a array and validate it with a loop to check the data integrity, but really specific field like only three string value possible, or one integer with 3 possible value, this method is not enough.
Specific container
So I build specific object container with a specific test in all my field in my object constructor. The code seams to be very heavy but really simple and obvious if you make if condition one by one (not in cascade). You can avoid mistype issue or copy past bugs with unit test, and cancel the construction of the object if something is missing or wrong.
JSON Validation
I assume you use json or xml to exchange data between your code and the REST API, seam to be obvious but JSON validation first give a good idea if you get all your information.
Hope it's help
Regards
Upvotes: 1