Better way to get default option?

I have something like:

Keyword.get(
  opts,
  :upload_path_changer,
  Application.get_env(
    :file_uploader,
    :upload_path_changer,
    MyApp.UploadPathChanger
  )
)

Get the :upload_path_changer module from options (opts);
if not found in options, get it from the config file;
if not found in the config file, use MyApp.UploadPathChanger.

Do you think the code above can improve in readability?

Something like this?

Keyword.get(opts, :upload_path_changer) || Application.get_env(:file_uploader, :upload_path_changer) || MyApp.UploadPathChager
3 Likes

Just make a helper in one of your modules. I also found such snippets very tiresome and just hid the complexity away in neat quick functions.

6 Likes

This will change semantics of the original, as opts = [upload_path_changer: nil] will return different results in original and this one.

Maybe merge options with defaults?

default_opts = [
  upload_patch_changer: Application.get_env(:file_uploader, :upload_patch_changer, MyApp.UploadPatchChanger)
  # other options if needed
]

opts = Keyword.merge(default_opts, opts)
4 Likes

I really like this approach, especially when there are several default options. ^^

1 Like

Haven’t considered that case. Though I doubt that there will be a module nil that happens to implement the behaviour…