简体   繁体   中英

Should I import strings into a class or use getString() to assign them to a variable?

I originally had all my url's for api calls as individual strings, but am updating to have a separate base url string and api endpoint string.

Previously I was using the getString() method to assign the string resource to a variable:

String USER_URL = getString(R.string.user_url);

But I found I could just import the string and use it directly:

import static com.chill.vbc.chill.R.string.base_url;

Is it best practice to just import all the strings you need for a class, or to retrieve them as needed and assign them to a local variable and why?

One of the design principles of software engineering is to try to use the smallest possible scope for anything that you declare in memory. This is good for a variety of reasons such as freeing memory and reducing naming collisions for variables. If you google the design principles around scope then you will find much more info.

For this design principle alone, I would suggest that you grab the string only when you need it.

Be very careful !

Doing the static import, you don't import the String value but it's id used by Android. So instead of getting my beautiful string with getString(R.string.user_url) calling it directly like this myString = R.string.user_url would result as an int.

If you explore your R class, you will see only public static final int key mapping.
eg public static final int R.string.user_url = 0x7f060021

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM