HiveBrain v1.2.0
Get Started
← Back to all entries
debugMinor

Fetching environment variables — can I use pattern matching?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
canenvironmentvariablesfetchingusepatternmatching

Problem

I've got the following Elixir code:

defmodule Envvar do
    def exists?(env) do :os.getenv(env) != false end

    def get(env) do 
        if exists?(env) do
            {env, :os.getenv(env)}
        else 
            {env, nil}
        end 
    end
end


Two things:

  • Am I using the ? correctly here? I'm assuming that any predicate function should have the ? on the end of the name by convention.



  • Is there a way to code the get function as a pattern match rather than a if/else? I'm asking here because I'm guessing that a pattern match would be more idiomatic Elixir code.

Solution

Using the ? for a boolean predicate is fine. At least it is what I would do in
Ruby and Elixir.

You won't be able to call exists?(env) in a guard clause so pattern matching does not win you much here.

You are calling :os.getenv() twice unneccessarily.
I'm not sure why you just want to convert 'false' to 'nil', here is a way:

defmodule Envvar do
  def get(env)
    do_get(:os.getenv(env))
  end

  defp do_get(false)
    {:env, nil}
  end

  defp do_get(result)
    {:env,result}
  end
end

Code Snippets

defmodule Envvar do
  def get(env)
    do_get(:os.getenv(env))
  end

  defp do_get(false)
    {:env, nil}
  end

  defp do_get(result)
    {:env,result}
  end
end

Context

StackExchange Code Review Q#43747, answer score: 6

Revisions (0)

No revisions yet.