I have some code that looks like this:
public Tuple<bool, SomeObjectModel> CheckIfJsonIsValid(string IncomingJson)
{
SomeObjectModel TheObjectModel = new SomeObjectModel();
JavascriptSerializer TheSerializer = new JavascriptSerializer();
.....
try
{
TheObjectModel = TheSerializer.Deserialize<SomeObjectModel>(IncomingJson);
}
catch
{
return new Tuple<bool, SomeObjectModel>(false, null); //question here
}
.....
return new Tuple<bool, SomeObjectModel>(true, TheObjectModel);
}
The calling method first check the returning tuple’s Item1, and if it’s false, ends its process.
Is it better practice a) to return a null value in the Tuple or b) to return a new and fresh instance of SomeObjectModel? Are there any performance implications?
Thanks for your suggestions.
Let me suggest three alternative solutions:
ParseJsonIfValid: If deserializing works, TheObjectModel is always non-null. Thus, there is no need for the boolean:
In the calling function simply check whether the return value is null or not.
ParseJson: If the JSON is usually valid, and invalid JSON is a sign of something gone terribly wrong, just throw an exception:
Be sure to include the inner (“real”) exception, so that the calling function can log the real cause of the error for debugging purposes.
TryParseJson: If
nullcan be a valid deserialization, you can use the following pattern, which has the advantage of being consistent with theTryParsemethods of the .NET framework: