Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Prefer ImmutableSet.of() instead of Set.of() in some cases #2318

Open
a-k-g opened this issue Jul 8, 2022 · 0 comments
Open

Prefer ImmutableSet.of() instead of Set.of() in some cases #2318

a-k-g opened this issue Jul 8, 2022 · 0 comments

Comments

@a-k-g
Copy link
Contributor

a-k-g commented Jul 8, 2022

What happened?

The Set.of() factory methods are a bit dangerous to use. If there are duplicate elements it will throw at runtime, for example:

String element1 = "hello";
String element2 = "hello";
Set<String> uniqueStrings = Set.of(element1, element2);

This is something we've stumbled over internally. The contract for ImmutableSet.of() allows duplicates on the other hand, which is what devs normally expect.

What did you want to happen?

I think the idea behind Set.of() to throw is to catch errors where users may have unintentionally specified duplicates. For instance it seems reasonable to throw if say you've accidentally written something like this:

private static final Set<Integer> BAD_STATUS_CODES = Set.of(
        400,
        401,
        401, // Bug: Likely should've been 404
        405);

It seems desirable to let this kind of usage ^ continue but in cases where the Set elements are not compile time constants it probably makes sense to warn and instead recommend ImmutableSet.of().


This is a low priority issue though as whenever it happens its really quick to diagnose and fix.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant