Best Practices
Get the most out of AndHow and your application
Last updated
Was this helpful?
Get the most out of AndHow and your application
Last updated
Was this helpful?
Just like constants, Properties can (and should) be declared where they are be used to create natural scope: If a secret is only needed by one class, don't make it visible to the entire application. Avoid placing Properties in a central 'Config' class.
Nesting related Properties into interfaces creates logical, canonical names for Properties. It also takes advantage of the Java language to save some typing: Variables declared in an interface are implicitly static final. As of Java 11, inner interfaces may be declared private.
Properties always have a unique canonical name based on their logical path. A Property named MY_PROP
declared in the com.bigcorp.MyClass
has the canonical name com.bigcorp.MyClass.MY_PROP
. The same pattern continues with nested inner classes or interfaces.
Properties may have aliases, but the canonical names are often good enough and will implicitly update when refactoring.
Don't use a default value for local workstation or test environment configuration values.
Its easy for a default value to end up in production. Some Properties have good defaults: report margin, retry counts or log level. Others do not: DB connection string, user name or password. If a Property has no value that is acceptable in all environments, its better to not specify a default and rely on configuration to supply the value.
AndHow allows only a single class implementing the interface on the classpath and will complain (i.e. throw a RuntimeException) at startup if it finds more. Why? AndHowIinit - it cannot be ambiguous which AndHowInit is intended to be the effective one. If an AndHowInit instance is included in a library, it prohibits applications using that library from creating their own AndHowInit.
If you have a dual-use library, such as a calculation utility that can be run from command line or bundled into a larger application, use a packaging tool like Maven to create two packaged version: One with an AndHowInit instance for independant usage, and another without an AndHowInit instance for so the library can be included as a dependency in other applications.
Incluing an andhow.properties file in a library is essentially just like setting default values for each Property. Properties already can have their defalaults declared in their construction, so there is no need to do this. Worse, if the deployed application includes its own properties file, it may become ambiguous which one is suppose to be in use (though web containers like Tomcat and SpringBoot generally get this right).
If you want to include a sample configuration file for applications using a library, it might be clearer to call it andhow.properties.sample or similar.