Is it sensible and efficient to set a List as a constant? Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Is it sensible and efficient to set a List as a constant? without wasting too much if your time.

The question is published on by Tutorial Guruji team.

Google’s Oauth2 library methods expect a Java list for the scopes argument. Is it sensible to code the argument as a List literal, like this:

public  static  final List<String> YOUTUBE_SCOPES = Lists.newArrayList(
      "https://www.googleapis.com/auth/youtube.upload",
      "https://www.googleapis.com/auth/youtube.readonly");

so that I can:

SendToGoogleUtils.getGoogleAccountCredential(activity, accountName, YOUTUBE_SCOPES );

Will the Java compiler create an efficient YOUTUBE_SCOPES literal?

Answer

ArrayLists are not immutable, even if they’re declared as final; that just means that variable cannot change, but its contents can. See: Why can final object be modified?

Since you’re using Lists.newArrayList, it looks like you’re using Guava. Guava has a great solution to this issue: ImmutableList. So your code would be:

public static final List<String> YOUTUBE_SCOPES = ImmutableList.of(
  "https://www.googleapis.com/auth/youtube.upload",
  "https://www.googleapis.com/auth/youtube.readonly");

That said, there’s one other concern here, and that’s “what if I want to change this later”?

I don’t know if you have any sort of configuration file loading, but just be aware that if you do need to change these scopes (if, say, Google changes the URLs), you will have to change your links. If it’s okay that this can be changed by recompiling your jar, then don’t worry about it; you may want to consider putting these magic constants into some sort of config file, though.

We are here to answer your question about Is it sensible and efficient to set a List as a constant? - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji