4
\$\begingroup\$

I have a method which extracts the logged-in user details from a SpringSecurityContext object.

I have read that only utility methods (which does certain calculations) should be static.

Here is my method; it doesn't seem to be a utility method but I don't find any reason why I shouldn't make it static as I am using it in multiple beans.

public static int getSignedUpUser()
 {
 final SecurityContext ctx = SecurityContextHolder.getContext();
 if(ctx != null)
 {
 final Authentication auth = ctx.getAuthentication();
 if(auth != null)
 {
 final Object principal = auth.getPrincipal();
 if(principal instanceof AUser)
 {
 final AUser au = (AUser)principal;
 return au.getId();
 }
 }
 }
 return 0;
 }
}
ferada
11.4k25 silver badges65 bronze badges
asked Feb 26, 2015 at 12:37
\$\endgroup\$

1 Answer 1

5
\$\begingroup\$

This is a utility method. There's nothing wrong with it being static. Its readability would benefit greatly from (a) using guard clauses instead of having multiple nesting levels, (b) using java bracket style, and (c) using java spacing. You might also want to add logging to indicate why there's no signed-in user, which is presumably a WARN or ERROR, but should at least be a DEBUG.

public static int getSignedUpUser() {
 final SecurityContext ctx = SecurityContextHolder.getContext();
 if (ctx == null) {
 LOGGER.debug("No security context available");
 return 0;
 }
 final Authentication auth = ctx.getAuthentication();
 if (auth == null) {
 LOGGER.debug("No authentication available in security context {}", ctx);
 return 0;
 } 
 final Object principal = auth.getPrincipal();
 if (!(principal instanceof AUser) {
 LOGGER.warn("Principal {} is not an instance of AUser!", principal);
 return 0;
 }
 final AUser au = (AUser)principal;
 return au.getId();
}
answered Feb 26, 2015 at 13:45
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.