Best practice for returning multiple values in Java?

前端 未结 7 1219
走了就别回头了
走了就别回头了 2020-12-05 17:31

Today I\'ve added a extra security check behind my login forms, to slow down brute force attacks. I\'ve got multiple login forms and made a nice easy to call function that d

7条回答
  •  情书的邮戳
    2020-12-05 18:20

    You can define a Pair class, and a Triplet class, and that would solve the problem of returning 2 and 3 values while ensuring type-safety. In this particular case, the signature could be

    public static boolean validateLogin(HttpServletRequest request,
                String email, String password, Pair outputIfOk);
    

    Or even better, in a servlet context, it may make sense to set some well-documented request attributes.

    If you find yourself needing special classes to return results very often, you can most likely refactor those clases to share a common ancestor (say, have a RequestStatus which includes the 'ok' and 'message' fields).

    Other than that, yes, you are being lazy -- custom clases will always be more self-documenting than Pairs and Triplets.

提交回复
热议问题