I'm writing a method that forms part of the public interface of a Java class. It broadly allows the caller to specify the values to assign to a number of database entities - so they must supply both the IDs of the entities themselves, and the values to assign to them.
I'm wavering between implementing this as a List<Pair<Integer, Integer>>
or just two List<Integer>
arguments. Both would obviously work, and neither would cause any implementation or efficiency problems within my method. It's basically the same information in any case (a 2xn array), just striped differently.
So I'd like some opinions on which one you think would be better, and why.
Advantages I see so far for the list of pairs:
Advantages for the pair of lists:
Pair
is to grasp as a concept)Both cases have identical type-safety, as well as the same possibility for argument mismatch (e.g. entering values first and IDs second when it should be the other way around). This latter problem can be avoided by creating a trivial wrapper around Integer
called something like PrimaryKey
, which has its own pros and cons and is orthogonal to this issue anyway as this can be used just as well in both cases.
However there's a middle ground that could feasibly be a third option - a trivial container class with integer fields for objectId and value. This doesn't enlist the compiler's help in ensuring the objects are correct through typing, but it does provide an extra layer of security in the assignments. I don't think I'd go for this, though, as I don't like the idea of polluting a public interface with a trivial class like this.
I would strongly recommend tying that data together, possibly as a Pair, but more as a specific container. That way you're at liberty to introduce extra functionality related to those two objects.
Keeping the two lists separate is going to be a pain. You'll have to pass both around together and keep them in sync. The overhead of creating a new object for this is negligible, and precisely what OOP is designed for (you'll be creaing non-JDK classes just by writing new Java code for your application, don't forget).
I create minor classes like this all the time. They enforce strong type safety and provide the scope for enhancement and refactoring. IDEs can more readily identify and perform refactorings.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With