4 tips to return multiple values
Java directly does not support returning multiple values from method. During time some workarounds were invented. I personally like Immutables approach.
Return array of values
Only one data type can be used, semantic of array items is not directly visible:
This brings many issues:
- Necessity to check length
- Test NULL values
- Semantics of fields is lost
- Only one data type can be used
Use higher structure like Pair, List, Map
Use for example Pair:
I don’t like this approach for the same reason as array - you lose semantics of fields and only one data type can be used.
Define returned type as class
Define nested/inner class with necessary members:
I don’t like accessing instance variables without accessors. But adding constructors/getters/setters is sooooo exhaustive. Fine for 2 fields but what about 10 or 20?
Newest possibility and my favorite is to use library called Immutables. It allows you to define interface using with getters and generates builder/access methods according to it:
This approach has many positive properties:
- Semantic is kept
- You may use arbitrary data types
- Basic validation is done automatically (NULL checks, …)
- You can define more complex validation using annotations