Scenario:
I have this code, which retrieves an access token.
private async Task<TokenResponse> GetTokenResponse(Credentials credentials, CancellationToken cancellationToken, string? scope = null)
{
var tokenResponse = await _httpClient.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest
{
RequestUri = new Uri("url that works", UriKind.Relative),
ClientId = credentials.ClientId!,
ClientSecret = credentials.ClientSecret,
Scope = scope
}, cancellationToken);
if (tokenResponse.IsError || string.IsNullOrEmpty(tokenResponse.AccessToken))
{
throw new AuthenticationException($"Error fetching token: {tokenResponse.Error}");
}
return tokenResponse;
}
Now I would like to use it in two ways:
Way 1.
public async Task<string> GetAccessTokenAsync(Credentials credentials, CancellationToken cancellationToken)
{
var tokenResponse = await GetTokenResponse(credentials, cancellationToken);
return tokenResponse.AccessToken;
}
This gives an possible null reference, because tokenResponse.AccessToken can be null.
Way 2.
public async Task<TokenResponse> GetAccessTokenWithScope(Credentials credentials, string scope, CancellationToken cancellationToken)
{
var tokenResponse = await GetTokenResponse(credentials, cancellationToken, scope);
return tokenResponse;
}
I need this to because I need the remaining properties of TokenResponse down the line, including the AccessToken.
The question:
In both of these approaches, I now need to check for null references even when I know for sure that the AccessToken is not null, as I've checked in the initial method GetTokenResponse when I got it. If TokenResponse was my class I could make the field required, but in this case it is not. How do you code against checking multiple times, or suppressing the warnings using the ! operator?
GetTokenResponse(credentials, cancellationToken, scope)
that always retun a non nullable valid object. Take a look at the NullObject design pattern.tokenResponse
is null. You only checked, if its propertyAccessToken
is null or empty.TokenResponse
class determines the format and it defines the access token as nullable. If you don't want that you'll have to create a new class to pass it down the line which defines the token as non-nullable.