0

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?

4
  • You can create a wrapper around GetTokenResponse(credentials, cancellationToken, scope) that always retun a non nullable valid object. Take a look at the NullObject design pattern. Commented Jul 9 at 14:25
  • You didn't check if tokenResponse is null. You only checked, if its property AccessToken is null or empty.
    – Ronnie
    Commented Jul 9 at 14:28
  • @Ronnie you're right, however this does not change the need to do null reference checks down the line. It'll continue giving a warning for a possible null reference when using tokenResponse.AccessToken.
    – Sirvis
    Commented Jul 9 at 14:39
  • Your 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.
    – NotFound
    Commented Jul 9 at 14:54

0

Browse other questions tagged or ask your own question.