Search code examples
javaout-parameters

Most user friendly way of passing back two variables in Java?


I'm writing a library that contains some hash functions.

I want one of the functions to return the hash (byte[]) and the random salt (byte[]) that was generated for use with the hash. What would be the most user friendly, and intuitive, way of doing this?

I have a C# version of this that works by returning the hash and then passing back the salt as an out parameter, which works perfectly, however Java doesn't give me the luxury of out parameters.

Any thoughts?


Solution

  • The most elegant way is of course to encapsulate the hash and salt in a class and return an instance of this class.

    class HashAndSalt {
        private byte[] hash, salt;
        public HashAndSalt(byte[] hash, byte[] salt) {
            this.hash = hash;
            this.salt = salt;
        }
    
        // access methods goes here
    }
    

    The main reason for choosing the above approach is that it becomes clear on the client side what the variables contain. If you return something like a byte[2][] I for one would keep forgetting if the hash was in index 0 or 1.

    If you make the fields final, some would probably even argue that you could make them public and skip the access-methods.