Best Practice for handling & naming intermediate/temporal variables in C#

153 views Asked by At

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?

2

There are 2 answers

0
Heinzi On BEST ANSWER

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(...));
0
Steven On

Usually when I need to name quick variables, then I do make them at least relatable to what they're supposed to retrieve, but I make it a shorter word, or a word without capitals, to indicate its short use.

like var doc = document or var collect = Collection.FirstOrDefault()

Still, I'd prefer not shortening them at all, and prioritise readability for it, as you need to understand it when someone else, or you a few months later, looks back at the code.