Skip to content

Instantly share code, notes, and snippets.

@axelson
Forked from sgyyz/base_calculator.ex
Last active May 7, 2019 03:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save axelson/0a9a61097b0e550a5d42a8718ecd562b to your computer and use it in GitHub Desktop.
Save axelson/0a9a61097b0e550a5d42a8718ecd562b to your computer and use it in GitHub Desktop.
Elixir Abstract and Extends
defmodule BaseCalculator do
@moduledoc """
Define the base calculator and provide public API.
Define the callback to implement specific logic in child module.
"""
# it should be implemented by child module
@callback do_calculate(num1 :: integer, num2 :: integer) :: {:ok, integer} | {:error, any()}
def calculate(module, num1, num2) do
module.do_calculate(num1, num2)
end
end
defmodule DivideCalculator do
@moduledoc """
Implement divide calculation logic
"""
@behaviour BaseCalculator
@impl BaseCalculator
def do_calculate(num1, num2) do
case num2 do
0 -> {:error, :invalid_param}
_ -> {:ok, num1 / num2}
end
end
end
defmodule PlusCalculator do
@moduledoc """
Implement plus calculation logic
"""
@behaviour BaseCalculator
@impl BaseCalculator
def do_calculate(num1, num2) do
{:ok, num1 + num2}
end
end
defmodule SubCalculator do
@moduledoc """
Implement substract calculation logic
"""
@behaviour BaseCalculator
@impl BaseCalculator
def do_calculate(num1, num2) do
{:ok, num1 * num2}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment