Best practice for returning multiple values in Java?

前端 未结 7 1175
走了就别回头了
走了就别回头了 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

    Here is a possible solution I picked up from another discussion, and enhanced a bit. It uses a public inner class with a private constructor:

    public class Test {
        // Internal storage unit for the two values:
        // 'name' and 'age'.
        private Pair info;
    
        public Test() {
            // Empty default constructor.
        }
    
        /**
         * The two values are stored in the Test class.
         *
         * @param name
         * @param age
         */
        public void setInfo(String name, int age) {
            info = new Pair<>(name, age);
        }
    
        /**
         * The 'name' and 'age' values are returned in a
         * single object.
         *
         * @return Both values in a Pair object.
         */
        public Pair getInfo() {
            return info;
        }
    
        /**
         *  This is an Inner Class for providing pseudo 'tuplet'
         *  as a 'get' return value.
         *
         * @param  first internally stored value.
         * @param  second internally stored value.
         */
        public class Pair {
    
            public final F first;
            public final S second;
    
            // This constructor is private to prevent
            // it being instantiated outside its
            // intended environment.
            private Pair(F first, S second) {
                this.first = first;
                this.second = second;
            }
    
            @Override
            public String toString(){
                return first + ", " + second;
            }
        }
    
        /**
         * main method for testing of the class only.
         *
         * @param args
         */
        public static void main(String args[]) {
            Test test = new Test();
    
            test.setInfo("Peter Smith", 35);
            Test.Pair pair = test.getInfo();
    
            System.out.println("name: " + pair.first);
            System.out.println("age: " + pair.second);
            System.out.println(pair.toString());
        }
    }
    

提交回复
热议问题