My concern with this code is that I am forcing execution repeatedly through the same pathway for the sake of a readability that I'm not convinced by.
It's a servlet filter which detects if the authenticated user is a service account (non-human) and then does some checks on them within the if
clause.
import org.springframework.security.core.Authentication;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
public class ServiceAccountFilter implements Filter {
@Override
public void doFilter(ServletRequest request,
ServletResponse response,
FilterChain chain)
throws IOException, ServletException {
if (request instanceof HttpServletRequest
&& ((HttpServletRequest) request).getUserPrincipal() != null
&& ((HttpServletRequest) request).getUserPrincipal()
instanceof Authentication
&& ((Authentication)
((HttpServletRequest) request).getUserPrincipal())
.getPrincipal() != null
&& ((Authentication)
((HttpServletRequest) request).getUserPrincipal())
.getPrincipal() instanceof MyUser
&& ((MyUser) ((Authentication)
((HttpServletRequest) request).getUserPrincipal())
.getPrincipal()).getUsername() != null
&& ((MyUser) ((Authentication)
((HttpServletRequest) request).getUserPrincipal())
.getPrincipal()).getUsername().length() > 6) {
MyUser myUser = (MyUser) ((Authentication)
((HttpServletRequest) request).getUserPrincipal())
.getPrincipal();
// app-specific tests
}
chain.doFilter(request, response);
}
Would it be better to instantiate all of these objects and create a deeply nested set of simplified if
clauses?
My opinion is that it might be marginally more performant but it wouldn't be any more readable - or am I already blind to how unreadable it is?
Authentication
andMyUser
classes for review. \$\endgroup\$