https://kotlinlang.org logo
#android
Title
# android
m

Michael Pohl

06/04/2020, 5:00 PM
Does anyone have an idea what would be the best practice for dealing with constants on Android today? As in, do I put them in companion objects or just have them at top level, and if so, how to organize that properly? What about private and public? I personally like companion object consts, but I'm being told that add makes them more expensive since the object needs to be instantiated. What is considered "right" here?
1
w

Waseef Akhtar

06/04/2020, 5:29 PM
I just put them at the top of the file where it’s used the most. Make it
const val
if it’s used in other classes as well, else
private const val
c

Cody Engel

06/04/2020, 5:45 PM
There isn't one right answer. I generally prefer adding constants as a companion object on the class where it's relevant, I've found the name spacing on the class is helpful. I've been guilty of having a
Constants
object in the past and after seeing it evolve over a year and a half I really grew to dislike that as it was easy to delete the classes where that constant was used but never delete the constant value itself. @Waseef Akhtar I haven't tried const top level within a file so I'm curious what techniques you've used. That sounds like a pretty good approach as well but I'm curious if you've ran into trouble with discoverability or if it's forced you into slightly more descriptive names?
w

Waseef Akhtar

06/04/2020, 6:25 PM
@Cody Engel I have used a
Constants
object as well, but it eventually grew pretty large. My current approach seems to be working better for me so far. Would love to hear from others as well though!
💯 1
m

Michael Pohl

06/04/2020, 6:27 PM
I am tending towards the benefits of the namespacing too - keeping things in order is just a lot easier that way. I wonder how well that works with just having them in the specific files. Will definitely try this.
👌 1
p

psh

06/04/2020, 9:19 PM
If your constants vary based on environment (for instance, URLS for endpoints in Dev / Qa / Prod) or another variant, you might want to define them in your
build.gradle
file per build type, product flavor or build variant so that they end up on your
BuildConfig
file.
m

Michael Pohl

06/05/2020, 5:15 AM
This is a good point. I'm actually doing this for everything applicable (as one should imho) , but there are some this would be overkill for. I've also found that I have to declare the same value for every environment even if they don't change (maybe I'm doing something wrong there...? ), so I reserve this practice for the ones that do change per env or get set by the CI (like secrets and such).