To prevent errors and potential security issues caused by assigning the wrong type of value to a variable
defmodule VulnerableCode do
def add_one(input) do
input + 1
end
end
This Elixir code is vulnerable because it assigns a string to a variable that is expected to be a number. If a string is supplied instead of a number, an error will occur when trying to perform an arithmetic operation.
defmodule SecureCode do
def add_one(input) when is_number(input) do
input + 1
end
def add_one(_input) do
{:error, "Input must be a number"}
end
end
This Elixir code is safe because it checks the type of the input before performing the arithmetic operation. If the input is not a number, an error message is returned instead of causing a runtime error.