Search code examples
c#asp.netstaticreadabilitymaintainability

Static and non-static version of the same function in C#


I have my own implementation of the GetUserId() function made static to be able to retrieve the ID in static context. But I also have many places where I use standard GetUserId() function built into an asp.net UserManager library. My fix for not using different logic for the same thing is overriding the non-static method and using the static one inside it (this is inside the UserManagerService class):

public override string GetUserId(ClaimsPrincipal user)
{
    return GetUserIdStatic(user);
}

public static string GetUserIdStatic(ClaimsPrincipal user)
{
    return user.FindFirst(ClaimTypes.NameIdentifier).Value;
}

I did that because I prefer to call the non-static method in the non-static context (generally it's over 90% of the calls). So I prefer to call _userManagerService.GetUserId(User) than UserManagerService.GetUserIdStatic(User) whenever I can.

From a readability and maintainability perspective (and eventual harmful consequences that I can't foresee right now) is it better to do it the way described above; switch all calls to the static version; or some other way that I didn't think of?


Solution

  • Making a static and non-static versions of a method that do the same thing is highly questionable.

    You should replace static method to get user id with a static method or a static property to get user manager service. This would let you obtain user id in static context by calling a non-static method:

    var userId = StaticGetUserManagerSerice().GetUserIdStatic(user);
    

    or

    var userId = UserManagerSerice.Instance.GetUserIdStatic(user);