forked from elixir-lang/elixir
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
"Primitive Obsession" added (Anti-pattern documentation)
- Loading branch information
Showing
1 changed file
with
40 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -5,7 +5,46 @@ play within a codebase. | |
|
||
## Primitive obsession | ||
|
||
TODO | ||
#### Problem | ||
|
||
This anti-pattern can be felt when Elixir basic types (for example, *integer*, *float*, and *string*) are abusively used in function parameters and code variables, rather than creating specific composite data types (for example, *structs*, and *map*) that can better represent a domain. | ||
|
||
#### Example | ||
|
||
An example of this anti-pattern is the use of a single *string* to represent an `Address`. An `Address` is a more complex structure than a simple basic (aka, primitive) value. | ||
|
||
```elixir | ||
defmodule Foo do | ||
@spec bar(String.t()) :: any() | ||
def bar(address) do | ||
# Do something with address... | ||
end | ||
end | ||
``` | ||
|
||
#### Refactoring | ||
|
||
We can create an `Address` struct to remove this anti-pattern, better representing this domain through a composite type. Additionally, we can modify the `bar/1` function to accept a parameter of type `Address` instead of a *string*. With this modification, we can extract each field of this composite type individually when needed. | ||
Check failure on line 27 in lib/elixir/pages/anti-patterns/design-anti-patterns.md GitHub Actions / Lint Markdown contentTrailing spaces
|
||
|
||
```elixir | ||
defmodule Address do | ||
defstruct street: nil, city: nil, state: nil, postal_code: nil, country: nil | ||
|
||
@type t :: %Address{street: String.t(), city: String.t(), state: String.t(), postal_code: integer(), country: String.t()} | ||
end | ||
``` | ||
|
||
```elixir | ||
defmodule Foo do | ||
@spec bar(Address.t()) :: any() | ||
def bar(address) do | ||
# Some other code... | ||
|
||
%Address{postal_code: zip} = address | ||
# Do something with zip... | ||
end | ||
end | ||
``` | ||
|
||
## Boolean obsession | ||
|
||
|