In my C# (.Net 6) backend (but also in other languages) I often face the problem, that I get an object which I need to validate and convert before using it. Currently I handle this by creating two variables: fooRaw
and foo
. I store the response to fooRaw
, then I validate it. After that I parse it and store the result into foo
.
I am not really convinced this is the best way of doing this - maybe someone out there can enlighten me or at least inspire me how I could improve this.
Two Examples:
Example 1:
List<FooType> fooRaw = GetFoos(filter: "id = '123'");
// id should be unique therefor only one result is valid
if(fooRaw.Count != 1){
throw //...
}
FooType foo = fooRaw.First();
Example 2:
string fooRaw = await httpResponse.Content.ReadAsStringAsync();
// I have a http response that i want to parse -> only works if string is not empty
if(!string.IsNullOrWhitespace(fooRaw)){
throw //...
}
FooType foo = JsonSerializer.Deserialize<FooType>(fooRaw);
Any Ideas how I could improve this process or at least improve variable naming and readability?
Your solution is fine, and the Raw
suffix nicely indicates that this a raw, un-validated value. I would probably use rawFoo
instead of fooRaw
, since it sounds more "natural" (and Visual Studio won't suggest to auto-complete fooRaw
if you start typing foo
), but that might be a matter of taste.
If you want to avoid having the raw variable in scope after validation (lest someone might accidentally use it instead of the validated value) and your validation logic just throws exceptions, you can extract your validation logic into a separate method and avoid the intermediate variable:
var foo = ValidateFoo(GetRawFoo(...));