Skip to content

Instantly share code, notes, and snippets.

@turboBasic
Last active September 14, 2021 15:33
Show Gist options
  • Save turboBasic/ea704534b82b428f32119c57d9135f75 to your computer and use it in GitHub Desktop.
Save turboBasic/ea704534b82b428f32119c57d9135f75 to your computer and use it in GitHub Desktop.
How to manage constants in Java/Groovy #java #groovy

Class as constants container

final class Constants {
    final class File {
        public static final int MIN_ROWS = 1
        public static final int MAX_ROWS = 1000
        private File() {}
    }

    final class DB {
        public static final String name = 'oups'

        final class Connection {
            public static final String URL = 'jdbc:tra-ta-ta'
            public static final String USER = 'testUser'
            public static final String PASSWORD = 'testPassword'
            private Connection() {}
        }

        private DB() {}
    }

    private Constants() {}
}

Than, for example, I use Constants.DB.Connection.URL to get constant. It looks more "object oriently" as for me.

Enum as constants container

Example 1

For example, here two values defined in a enum class (so constant out of the box):

public enum MyEnum {

    ONE_CONSTANT('value'), 
    ANOTHER_CONSTANT('another value')

    private String value

    MyEnum(String value) {
       this.value = value
    }
    ...
}

Here a method that expects to have one of these enum values as parameter:

public void process(MyEnum myEnum){
    ...    
}


//  Use
process MyEnum.ONE_CONSTANT
process MyEnum.ANOTHER_CONSTANT

Example 2

class OfficePrinter {
    public enum PrinterState { 
        Ready, PCLoadLetter, OutOfToner, Offline;
    }
    public static final PrinterState STATE = PrinterState.Ready
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment