Search code examples
javaandroidclassconstants

Putting all constants in one class android


There are similar posts to mine but they date back to early 2010's so I'm not sure if things have changed. I just got some code review back and the reviewer suggested I put all of my constants in one class and call them from there. How can I do this and is this the right way to go? How do I declare and call them?


Solution

  • Whether it's "the right way" or not is mainly a matter of taste. There is no right or wrong here.

    As to how to use them - simply have a class with a series of public static final fields:

    public class Constants {
        public static final String FIRST_NAME = "Tarik";
        public static final String LAST_NAME = "Hodzic";
    }
    

    And then other classes can just use them:

    public class SomeClass {
        public String getFullName() {
            return Constants.FIRST_NAME + " " + Constants.LAST_NAME;
        }
    }