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

FR: Prefer ImmutableSet.toImmutableSet() over Collectors.toSet() for public static final fields #620

Open
iamdanfox opened this issue Apr 30, 2019 · 4 comments

Comments

@iamdanfox
Copy link
Contributor

What happened?

In an internal library, we a nice public static final field:

public static final Set<String> WHITELISTED_HEADERS = ImmutableSet.of(
    HttpHeaders.ACCEPT,
    ...
).stream().map(String::toLowerCase).collect(Collectors.toSet());

But it turns out that Collectors.toSet() gives us a mutable HashMap, so anyone could actually just access this WHITELISTED_HEADERS field and add/remove stuff!!

What did you want to happen?

I think we should write an error-prone check to just prefer the toImmutableSet() collector!

 public static final Set<String> WHITELISTED_HEADERS = ImmutableSet.of(
     HttpHeaders.ACCEPT,
     ...
-).stream().map(String::toLowerCase).collect(Collectors.toSet());
+).stream().map(String::toLowerCase).collect(ImmutableSet.toImmutableSet());
@markelliot
Copy link
Contributor

Probably should only fire this if the thing being set is final.

@schlosna
Copy link
Contributor

schlosna commented May 7, 2019

Does this get caught by promoting https://errorprone.info/bugpattern/MutableConstantField to error? That would also flag the downstream modification via https://errorprone.info/bugpattern/ImmutableModification

@stale
Copy link

stale bot commented Sep 23, 2019

This issue has been automatically marked as stale because it has not been touched in the last 60 days. Please comment if you'd like to keep it open, otherwise it'll be closed in 7 days time.

@stale stale bot added the stale label Sep 23, 2019
@iamdanfox iamdanfox removed the stale label Sep 23, 2019
@iamdanfox
Copy link
Contributor Author

In Java9+, we might actually want to recommend Collectors.toUnmodifiableList() as this uses the new List.of() implementation under the hood rather than relying on guava :)

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

No branches or pull requests

3 participants