Reputation: 3091
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?
Upvotes: 3
Views: 996
Reputation: 726849
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);
Upvotes: 2
Reputation: 184
Firstly it's not clear which class you're putting this static and non-static method in.
It seems your method is what's known as a "pure function", i.e. it simply returns the same thing regardless of the input and has no side effects. In this case it doesn't really make sense for the method to be for an instance, as it doesn't deal with the instance's data. So from that point of view, calls should be made static.
However, in accordance with OOP principals, it seems like the best place for this method would be in the User
class, as a non-static method.
Upvotes: 1