Hacker News new | past | comments | ask | show | jobs | submit login

Easy fix (if it's the shared, mutable state which bugs you):

* Create one class responsible for ingesting env vars at startup.

* Call it from main, and abort early with nice messages if it fails to read something.

* Now you have a nice (preferably immutable) class which guarantees the config is in a 'good state', and is self-documenting because it lists all the keys it uses to lookup env vars with.




This is essentially what I do in Rails apps. The only reference to an env var is in an initializer that sets an option in the global rails config structure.


The mutable state can be helpful. It is sometimes helpful to be able to change an app’s config without having to restart it. Ingesting the envs on startup into a class removes this ability.


Please, never do that on a server.

It's ok for interactive applications, but if you are writing a CLI command (what is different from an interactive CLI application), a system library or a deamon, don't ever let the same application that uses a configuration also change it.

When your non-interactive programs do that and anything at all goes wrong, it's basically impossible to determine the source of the problem. Also, it is common that bugs that one could just avoid triggering by configuration now become unavoidable.

(But if you mean reload the config after getting a SIGHUP or something like that, yeah, this is ok, and the best way to do that is by restarting everything on your program, even if you keep the same process, so your read-once class won't be a problem.)


thats quite an antipattern in production.

Immutable config via a config class that can exit early (prefereably startup) if there is a misconfiguration


If The same pattern works well in python at the module level, if your application is setup as a package. A module config.py sets a bunch of python variables like

    import os
    
    ENV_VAR=os.environ.get('ENV_VAR', default_value)
then the rest of the application can grab configuration with

    from .config import ENV_VAR
Since the assignment code executes on import, all config is read in when any piece of it is first used, consistency checks and logging can be written into the config.py module as normal python statements, config values can be cast to appropriate types (raising exceptions if they fail), etc.


In node.js there are quite a few packages that do exactly this - it's a great pattern and forces you to define which env values you will rely on in one place, rather than dripping them all over your codebase.


This is more or less the way I handle configuration in most applications that I create. +1


Agreed - this solution works well, and works nicely with statically typed languages.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: