Readable code with objects, constants & attributes
Occasionally when working with external APIs, you need to send over some cryptic status:
postData(
`http://example.com/orders/123`,
{ status: 2 }
)
But what does 2 mean?!
We can use objects to make this a bit easier to maintain
const STATUS = { processing: 0, error: 1, completed: 2 }
postData(
`http://example.com/orders/123`,
{ status: STATUS.completed }
)
Now we can immediately see the order status is completed.
This technique is applicable in other languages as well:
Ruby with a constant:
STATUS = { error: 0, processing: 1, completed: 2 }
STATUS[:completed]
Elixir as a module attribute
defmodule Order do
@status %{error: 0, processing: 1, completed: 2}
def completed, do: @status.completed
end
Tweet